問題描述
情況:我有一個自定義對象的 TreeSet,并且我還使用了一個自定義比較器.我創(chuàng)建了一個迭代器以在此 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 循環(huán)中向 TreeSet 添加一個新元素,那么該新元素是否會立即排序.換句話說,如果我在 while 循環(huán)中添加一個新元素并且它小于我當(dāng)前在 c 中保存的元素,那么在下一次迭代中,我會在 c 中獲得與上一次迭代中相同的元素嗎?(因為經(jīng)過排序后,新添加的元素會占據(jù)當(dāng)前元素之前的某個位置).
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).
推薦答案
如果您在迭代期間添加一個元素,您的下一次迭代器調(diào)用可能會拋出 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.
要迭代和添加元素,您可以先復(fù)制到另一個集合:
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 的建議創(chuàng)建一個單獨的集合,以便在迭代后與 ts
合并.
or create a separate collection to be merged with ts
after iteration, as Colin suggests.
這篇關(guān)于在 TreeSet 上使用迭代器的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!