Store distinct ip address in HashSet [duplicate]

为君一笑 提交于 2019-12-13 10:54:37

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!