英文:
Remove duplicates from ArrayList<JsonJavaObject> or how to find out if a similar item already exists in arraylist?
问题
我有一个 JsonJavaObject 的 ArrayList 集合(源自 com.ibm.commons.util.io.json.*)。当添加更多项时,我想检查 ArrayList 中是否已经存在类似的 JSsonObject。我该如何做呢?
或者我可以考虑只是继续用更多的 JsonJavaObject 填充 ArrayList,在返回结果之前合并重复项。
然而,当我尝试这样做,例如通过以下方式:
TreeSet<JsonJavaObject> uniqueHits = new TreeSet<JsonJavaObject>(JSONObjects);
ArrayList<JsonJavaObject> finalHits = new ArrayList<>(uniqueHits);
我会得到一个异常:
java.lang.ClassCastException: com.ibm.commons.util.io.json.JsonJavaObject 无法转换为 java.lang.Comparable
位于
TreeSet<JsonJavaObject> uniqueHits = new TreeSet<JsonJavaObject>(JSONObjects);
谁可以帮助我?
英文:
I have a ArrayList collection of JsonJavaObject (derived from 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?
Alternatively I can think of just filling the arraylist with more JsonJavaObject and before returning the result merge the duplicates.
However when I try this e.g. 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
at
TreeSet<JsonJavaObject> uniqueHits = new TreeSet<JsonJavaObject>(JSONObjects);
Who can help me?
答案1
得分: 1
TreeSet
需要类实现Comparable
接口,因为它希望根据某个定义的顺序对元素进行排序。对于去除重复项来说,这是不必要的,你可以简单地使用HashSet
,即:
Set<JsonJavaObject> uniqueHits = new HashSet<>(JSONObjects);
List<JsonJavaObject> finalHits = new ArrayList<>(uniqueHits);
英文:
TreeSet
needs the class to implement Comparable
since it wants to sort the elements according to some defined order.
Since this is unnecessary for duplicate elimination you can simply use a HashSet
i.e.
Set<JsonJavaObject> uniqueHits = new HashSet<>(JSONObjects);
List<JsonJavaObject> finalHits = new ArrayList<>(uniqueHits);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论