在 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 上使用迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)