2

我有以下代码用于对 ConcurrentHashMap 进行排序:

ConcurrentHashMap<String,String> text = new ConcurrentHashMap<String,String>();
.... 
List<String> list = new ArrayList<String>(text.values());
Collections.sort(list);

引发 NoSuchElementException:

Caused by: java.util.NoSuchElementException
        at library.ArrayList$Itr.next(ArrayList.java:1232)
        at library.ArrayList$ListItr.next(ArrayList.java:1263)
        at java.util.Collections.sort(Collections.java:120)

我不知道为什么。有任何想法吗?

4

2 回答 2

3

根据java api

NoSuchElementException 由枚举的 nextElement 方法引发,指示枚举中没有更多元素。

我在本地测试了以下代码

ConcurrentHashMap<String, String> t = new ConcurrentHashMap<String, String>();

List<String> al = new ArrayList<String>(t.values());
Collections.sort(al);

System.out.println("no bugs");

(使用 Eclipse jdk 1.5)我得到了预期的输出。在将一些键值对放入 ConcurrentHashMap 后,我还运行了本地测试,没有任何问题。根据我的成功,似乎以下一项(或两项)导致了我们的结果之间的差异。

A) 我们使用不同的类实现(我使用 jdk 1.5 中的 java.util.concurrent.ConcurrentHashMap、java.util.List、java.util.ArrayList)

B)您正在修改ArrayListConcurrentHashMap同时迭代器正在迭代所述对象的内容。运行排序时是否发生异常?我最好的猜测是,在您进行排序时,另一个线程正在弄乱您的ArrayList(因为ConcurentHashMap应该是线程安全的)。

于 2010-08-18T02:15:00.903 回答
-1

为排序创建一个新的 ArrayList 是不必要的,因此,您可以这样做:

ConcurrentHashMap<String,String> text = new ConcurrentHashMap<String,String>();
List<String> textList=text.values(); //unmodifiable List here.
Collections.sort(textList);// it also can sort.

:EOF

于 2010-08-18T02:17:13.067 回答