在java ConcurrentHashMap中对值进行排序
我有以下用于排序ConcurrentHashMap的代码:在java ConcurrentHashMap中对值进行排序,java,sorting,concurrenthashmap,Java,Sorting,Concurrenthashmap,我有以下用于排序ConcurrentHashMap的代码: ConcurrentHashMap<String,String> text = new ConcurrentHashMap<String,String>(); .... List<String> list = new ArrayList<String>(text.values()); Collections.sort(list); 我不知道为什么。有什么想法吗?根据 无接触元素异常 由
ConcurrentHashMap<String,String> text = new ConcurrentHashMap<String,String>();
....
List<String> list = new ArrayList<String>(text.values());
Collections.sort(list);
我不知道为什么。有什么想法吗?根据
无接触元素异常
由
枚举以指示存在
枚举中没有更多元素
我在本地测试了以下代码
ConcurrentHashMap<String, String> t = new ConcurrentHashMap<String, String>();
List<String> al = new ArrayList<String>(t.values());
Collections.sort(al);
System.out.println("no bugs");
ConcurrentHashMap t=new ConcurrentHashMap();
List al=新的数组列表(t.values());
集合。排序(al);
System.out.println(“无错误”);
(使用EclipseJDK1.5)我得到了预期的输出。在将一些键值对放入ConcurrentHashMap后,我还运行了本地测试,没有出现任何问题。根据我的成功经验,以下一项(或两者)似乎导致了我们结果之间的差异
A) 我们使用不同的类实现(我使用JDK1.5中的java.util.concurrent.ConcurrentHashMap、java.util.List、java.util.ArrayList)
B) 当迭代器遍历所述对象的内容时,您正在修改
ArrayList
或ConcurrentHashMap
的内容。运行排序时是否发生异常?我最好的猜测是,在排序时,另一个线程正在干扰您的ArrayList
(因为concurrenthashmap
应该是线程安全的) 无需创建新的ArrayList进行排序,因此,您可以这样做:
ConcurrentHashMap<String,String> text = new ConcurrentHashMap<String,String>();
List<String> textList=text.values(); //unmodifiable List here.
Collections.sort(textList);// it also can sort.
ConcurrentHashMap text=new ConcurrentHashMap();
List textList=text.values()//不可修改的列表在这里。
集合。排序(文本列表);//它还可以排序。
:EOF您可以发布重现问题所需的完整源代码吗?在类路径上是否有其他ArrayList?“library.ArrayList”似乎不正确。
library.ArrayList
绝对不是标准的ArrayList
,它存在于java.util.ArrayList
中。确保使用了正确的库,并仔细检查类路径。使用Java7时,java.lang.ClassCastException失败:java.util.concurrent.ConcurrentHashMap$值不能转换为java.util.List
ConcurrentHashMap<String,String> text = new ConcurrentHashMap<String,String>();
List<String> textList=text.values(); //unmodifiable List here.
Collections.sort(textList);// it also can sort.