简体   繁体   English

从 ArrayList 中删除重复项<jsonjavaobject>或者如何找出 arraylist 中是否已经存在类似的项目?</jsonjavaobject>

[英]Remove duplicates from ArrayList<JsonJavaObject> or how to find out if a similar item already exists in arraylist?

I have a ArrayList collection of JsonJavaObject (derived from com.ibm.commons.util.io.json.*).我有一个 ArrayList 的 JsonJavaObject 集合(源自 com.ibm.commons.util.io.json.*)。 When adding more items I would like to check if a similar JSsonObject already exists in the arraylist. How must I do this?添加更多项目时,我想检查 arraylist 中是否已经存在类似的 JSsonObject。我该怎么做?

Alternatively I can think of just filling the arraylist with more JsonJavaObject and before returning the result merge the duplicates.或者我可以考虑用更多的 JsonJavaObject 填充 arraylist 并在返回结果之前合并重复项。

However when I try this eg via但是,当我尝试这个时,例如通过

TreeSet<JsonJavaObject> uniqueHits = new TreeSet<JsonJavaObject>(JSONObjects);
ArrayList<JsonJavaObject> finalHits = new ArrayList<>(uniqueHits);

I get an exception: java.lang.ClassCastException: com.ibm.commons.util.io.json.JsonJavaObject incompatible with java.lang.Comparable我得到一个例外:java.lang.ClassCastException:com.ibm.commons.util.io.json.JsonJavaObject 与 java.lang.Comparable 不兼容

at

TreeSet uniqueHits = new TreeSet(JSONObjects); TreeSet uniqueHits = new TreeSet(JSONObjects);

Who can help me?谁能帮我?

TreeSet needs the class to implement Comparable since it wants to sort the elements according to some defined order. TreeSet需要 class 来实现Comparable ,因为它希望根据某个定义的顺序对元素进行排序。
Since this is unnecessary for duplicate elimination you can simply use a HashSet ie由于这对于重复消除是不必要的,您可以简单地使用HashSet

Set<JsonJavaObject> uniqueHits = new HashSet<>(JSONObjects);
List<JsonJavaObject> finalHits = new ArrayList<>(uniqueHits);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM