Malin
Malin

Reputation: 697

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.*). 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 uniqueHits = new TreeSet(JSONObjects);

Who can help me?

Upvotes: 1

Views: 51

Answers (1)

Turamarth
Turamarth

Reputation: 2282

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);

Upvotes: 1

Related Questions