在 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.
相关文章