在 TreeSet 上使用迭代器

Using iterator on a TreeSet(在 TreeSet 上使用迭代器)
本文介绍了在 TreeSet 上使用迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

情况:我有一个自定义对象的 TreeSet,并且我还使用了一个自定义比较器.我创建了一个迭代器以在此 TreeSet 上使用.

SITUATION: I have a TreeSet of custom Objects and I have also used a custom Comparator. I have created an iterator to use on this TreeSet.

TreeSet<Custom> ts=new TreeSet<Custom>();
Iterator<Custom> itr=ts.iterator();
while(itr.hasNext()){
    Custom c=itr.next();
    //Code to add a new element to the TreeSet ts
}

问题:好吧,我想知道,如果我在 while 循环中向 TreeSet 添加一个新元素,那么该新元素是否会立即排序.换句话说,如果我在 while 循环中添加一个新元素并且它小于我当前在 c 中保存的元素,那么在下一次迭代中,我会在 c 中获得与上一次迭代中相同的元素吗?(因为经过排序后,新添加的元素会占据当前元素之前的某个位置).

QUESTION: Well I want to know that if I add a new element to the TreeSet within the while loop, then will that new element get sorted immediately. In other words, if I add a new element within the while loop and it is less than the one which I am currently holding in c, then in the next iteration will I be getting the same element in c as in the last iteration?(since after sorting, the newly added element will occupy a place somewhere before the current element).

推荐答案

如果您在迭代期间添加一个元素,您的下一次迭代器调用可能会抛出 ConcurrentModificationException.请参阅 TreeSet 文档中的快速失败行为.

If you add an element during your iteration, your next iterator call will likely throw a ConcurrentModificationException. See the fail-fast behavior in TreeSet docs.

要迭代和添加元素,您可以先复制到另一个集合:

To iterate and add elements, you could copy first to another set:

TreeSet<Custom> ts = ...
TreeSet<Custom> tsWithExtra = new TreeSet(ts);

for (Custom c : ts) {
  // possibly add to tsWithExtra
}

// continue, using tsWithExtra

或者按照 Colin 的建议创建一个单独的集合,以便在迭代后与 ts 合并.

or create a separate collection to be merged with ts after iteration, as Colin suggests.

这篇关于在 TreeSet 上使用迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Reliable implementation of PBKDF2-HMAC-SHA256 for JAVA(PBKDF2-HMAC-SHA256 for JAVA 的可靠实现)
Correct way to sign and verify signature using bouncycastle(使用 bouncycastle 签名和验证签名的正确方法)
Creating RSA Public Key From String(从字符串创建 RSA 公钥)
Why java.security.NoSuchProviderException No such provider: BC?(为什么 java.security.NoSuchProviderException 没有这样的提供者:BC?)
Generating X509 Certificate using Bouncy Castle Java(使用 Bouncy Castle Java 生成 X509 证书)
How can I get a PublicKey object from EC public key bytes?(如何从 EC 公钥字节中获取 PublicKey 对象?)