在TreeSet上使用迭代器 [英] Using iterator on a TreeSet

查看:330
本文介绍了在TreeSet上使用迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况:我有一个TreeSet的自定义对象,我也使用了自定义比较器。我已经创建了一个迭代器在这个TreeSet上使用。

  TreeSet< Custom> ts = new TreeSet< Custom>(); 
迭代器< Custom> itr = ts.iterator();
while(itr.hasNext()){
Custom c = itr.next();
//为TreeSet添加新元素的代码ts
}

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

解决方案

你的迭代,你的下一个迭代器调用可能会抛出一个 ConcurrentModificationException 。请参见 TreeSet 文档中的快速故障行为。 p>

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

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

for(Custom c:ts){
//可能添加到tsWithExtra
}

//继续使用tsWithExtra

或创建单独的集合以在迭代后与 ts 正如Colin建议的那样。


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
}

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).

解决方案

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

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆