在HashSet中存储不同的IP地址 [英] Store distinct ip address in HashSet
本文介绍了在HashSet中存储不同的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
HashSet的最大大小
Possible Duplicate:
Maximum Size of HashSet
如何在HashSet中添加不同的IP地址
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;
}
推荐答案
add()
如果它是新值,则返回true
,因此:
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.
这篇关于在HashSet中存储不同的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文