gpt4 book ai didi

java - 对 java ConcurrentHashMap 中的值进行排序

转载 作者:行者123 更新时间:2023-11-30 09:54:08 28 4
gpt4 key购买 nike

我有以下用于排序 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)

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

最佳答案

根据java api

NoSuchElementException Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.

我在本地测试了以下代码

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 应该是线程安全的)。

关于java - 对 java ConcurrentHashMap 中的值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3507861/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com