Set.size() 与迭代器中的元素数量不匹配
为什么 Set.size() 与集合迭代器中的元素数量不匹配?
我正在使用 HashSet,并且添加了一些重复的值。因为我使用了一组,所以这些重复项被自动消除。 Set.size() 返回 16。当我实际迭代元素时,我得到 13。
是什么导致了这种差异?我做得对吗?
Set set = new HashSet();
...
System.out.println ("Found " + set.size() + " tokens...");
Iterator it = set.iterator();
int i = 0;
while (it.hasNext()) {
i++;
System.out.println(Integer.toString(i) + ": " + (String)it.next());
}
这是控制台的输出:
Found 16 tokens...
1: 3 Months Free HD Extra Pack
2: Best Buy - $30 for 3 Months (Instant Rebate)
3: Gift Card - Fry's - $100 (HDTV Offer)
4: 6 Months FREE Showtime
5: 3 Months Free HD Access
6: Savings Certificate Booklet
7: 3 months FREE Showtime (rolls off month 4)
8: Free NASCAR Hotpass
9: 3 Months Free DVR Service
10: $0 Delivery & Handling
11: 1 Year Free Showtime
12: $99 Off Advance Equipment (2nd AP)
13: Best Buy - $30 for 12 Months (Instant Rebate)
Why doesn't Set.size() match the number of elements in the set's iterator?
I'm using a HashSet, and I added some duplicate values. Those duplicates were automatically eliminated since I used a set. Set.size() is returning 16. When I actually iterate over the elements, I get 13.
What can be causing this difference? Am I doing it right?
Set set = new HashSet();
...
System.out.println ("Found " + set.size() + " tokens...");
Iterator it = set.iterator();
int i = 0;
while (it.hasNext()) {
i++;
System.out.println(Integer.toString(i) + ": " + (String)it.next());
}
Here's the output from the console:
Found 16 tokens...
1: 3 Months Free HD Extra Pack
2: Best Buy - $30 for 3 Months (Instant Rebate)
3: Gift Card - Fry's - $100 (HDTV Offer)
4: 6 Months FREE Showtime
5: 3 Months Free HD Access
6: Savings Certificate Booklet
7: 3 months FREE Showtime (rolls off month 4)
8: Free NASCAR Hotpass
9: 3 Months Free DVR Service
10: $0 Delivery & Handling
11: 1 Year Free Showtime
12: $99 Off Advance Equipment (2nd AP)
13: Best Buy - $30 for 12 Months (Instant Rebate)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
说真的,这是不可能的。 HashSet 是一个足够完善的类,不可能出现您所描述的错误。您可以通过以下一些方法来实现这一目标:
Seriously this is not possible. HashSet is a well-established enough class that there is no possibility of a bug like you describe being in it. Here are some ways you could make this happen:
因为你使用了反射:
不过说真的,这是我能想到的获得这些结果的唯一方法,假设你使用的是标准 HashSet 而不是某些第三方 HashSet。现在我无法想象您会使用反射来执行此操作,但又无法理解您的结果,因此我认为您在告诉我们的事情上犯了错误(例如, set 实际上不是本地的,而是可以被另一个线程访问)。
Because you used reflection:
Seriously though, that's the only way I can think of that you'd get these results, assuming you're using the standard HashSet and not some 3rd party one. Now I can't imagine you would be using reflection to do this and yet wouldn't understand your results, so I assume you're mistaken in something that you're telling us (for instance, set isn't actually local but is accessible by another thread).