Java equals Method

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Complex { 
private double re, im;

public Complex(double re, double im) {
this.re = re;
this.im = im;
}
// Overriding equals() to compare two Complex objects
@Override
public boolean equals(Object o) {
if (o == null) { return false; }
if (o == this) { return true; }
if (!(o instanceof Complex)) { return false; }
Complex c = (Complex) o;
// Compare the data members and return accordingly
return Double.compare(re, c.re) == 0
&& Double.compare(im, c.im) == 0;
}
}

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.

0%