Met an issue with the contains()
method, not sure why it behaves differently in the two scenarios, as the following code snippet shows:
import java.awt.*;
import java.util.LinkedHashSet;
import java.util.Set;
public class SetDemo01 {
public static void main(String[] args) {
Set<Point> set = new LinkedHashSet<>();
Point a = new Point(0, 1);
Point b = new Point(0, 1);
set.add(a);
System.out.println(set.contains(b));
Set<Coordinate> set02 = new LinkedHashSet<>();
Coordinate c = new Coordinate(0, 1);
Coordinate d = new Coordinate(0, 1);
set02.add(c);
System.out.println(set02.contains(d));
}
}
class Coordinate {
int x;
int y;
Coordinate (int x, int y) {
this.x = x;
this.y = y;
}
}
The console prints:
true
false
Now I knew I need to override the equals()
& hashCode()
methods, but could someone pls show the reference for this: when apply the contains()
method, the equals()
is run, and the 'hashCode' is compared.