One trick of JAVA’s TreeSet

Background

 I used to meet a bug while using a TreeSet to save & order some objects. I found some objects are lost although they are totally different with other objects.

What happened

According to the official document of JAVA, TreeSet exactly uses TreeMap to save elements. Not like HashMap and HashSet, TreeMap uses Comparator other than Objects’ hashCode and equals() to remove duplicates. If Comparator return 0, TreeSet or TreeMap don’t add the element into itself.

In this case, my Comparator compares one integer variable called size, which only depends on the size of an input object. So that all objects with the same size value have been defined as the same, only the first one can be kept.

Solution

  1. Update Comparator
  2. Change to other Sorted Set

Leave a Reply

Your email address will not be published. Required fields are marked *