HashSet的最大大小

ars*_*nal 2 java hashset

所以基本上我生成随机的10000个IP地址,我想存储在HashSet中找到的所有那些IP地址,但根据我的计算,发现大约6000个ip地址,但在HashSet中只有700个ip地址被存储了?在存储String方面HashSet是否有任何限制.任何建议将不胜感激.

   Set<String> ipFine = new HashSet<String>();
        long runs = 10000;
            while(runs > 0) {

            String ipAddress = generateIPAddress();

            resp = SomeClass.getLocationByIp(ipAddress);

            if(resp.getLocation() != null) {

                 ipFine.add(ipAddress);
                        }

               runs--;

         }
Run Code Online (Sandbox Code Playgroud)

Boh*_*ian 5

就你而言,没有限制(限制是数组的最大大小,即2**31).

但是,Sets只存储唯一值,所以我猜你只生成了700个唯一地址.

修改您的代码如下:

if(resp.getLocation() != null) {
    if (ipFine.add(ipAddress)) { // add() returns true if the value is unique
        runs--; // only decrement runs if it's a new value
    }
}
Run Code Online (Sandbox Code Playgroud)

此修改意味着您将保持循环,直到获得10000个唯一值.