问题
Possible Duplicate:
Maximum Size of HashSet
How can I add distinct ip address in HashSet
Set<String> ips = new HashSet<String>();
String ip = generateIPAddress();
if (!ips.add(ip)) {
// What should I do here?
}
private String generateIPAddress() {
Random r = new Random();
//Now the IP is b1.b2.b3.b4
String s = r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256);
return s;
}
回答1:
add()
returns true
if it's a new value, so:
while (!ips.add(ip)) {
ip = generateIPAddress(); // try again
}
This keeps looping until you add a new unique value.
Theoretically it could loop forever, but if your random generator is reasonable it will eventually find a new unique value.
来源:https://stackoverflow.com/questions/9745459/store-distinct-ip-address-in-hashset