2012-03-16 157 views
-2

可能重複:
Maximum Size of HashSet商店不同的IP地址

我怎樣才能在HashSet中添加不同的IP地址

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; 

    } 
+4

作業??? http://stackoverflow.com/questions/9745214/maximum-size-of-hashset – Bohemian 2012-03-16 22:51:49

+4

你的問題到底是什麼? – gobernador 2012-03-16 22:56:11

回答

0

add()回報true如果它是一個新的價值,所以:

while (!ips.add(ip)) { 
    ip = generateIPAddress(); // try again 
} 

這會持續循環,直到您添加新的唯一值。

理論上它可以永久循環,但如果你的隨機生成器是合理的,它將最終找到一個新的唯一值。