HashSet的最大大小

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

   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--;

}

回答:

就您而言,没有限制(限制是数组的最大大小,即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

}

}

此修改将意味着您将一直循环播放,直到获得10000个 唯一 值为止。

以上是 HashSet的最大大小 的全部内容, 来源链接: utcz.com/qa/398717.html

回到顶部