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

huangapple go评论75阅读模式
英文:

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&lt;JsonJavaObject&gt; uniqueHits = new TreeSet&lt;JsonJavaObject&gt;(JSONObjects);
ArrayList&lt;JsonJavaObject&gt; finalHits = new ArrayList&lt;&gt;(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&lt;JsonJavaObject&gt; uniqueHits = new HashSet&lt;&gt;(JSONObjects);
List&lt;JsonJavaObject&gt; finalHits = new ArrayList&lt;&gt;(uniqueHits);

huangapple
  • 本文由 发表于 2020年10月27日 23:12:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/64557384.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定