This is the first Java post in my blog, actually I have lots of summaries about Java in recently years, they just get accumulated so I decide to post here.
Also, start from next week, I will dive into API work.
When you define a new class and it will deal with hash thing, don’t forget to overwrite the equals
method, or compare
method if they need to be sorted in natural order, or implement Comparator
interface for ordering by other rules.
For example:
1 | class Complex { |
https://stackoverflow.com/questions/16970210/java-treeset-remove-and-contains-not-working
One thing I want to emphasize is TreeSet
, the object in tree set use its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.
To be more accurate, TreeSet
is an implementation of SortedSet
If you want a .equals()/.hashCode()
compatible set, use, for instance, a HashSet.