public class Apple {
private final int weight;
public Apple(int weight) {
this.weight = weight;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Apple apple = (Apple) o;
return weight == apple.weight;
}
@Override
public int hashCode() {
return Objects.hashCode(weight);
}
public static void main(String[] args) {
Apple apple = new Apple(100);
Apple anotherApple = new Apple(100);
System.out.println(apple.equals(anotherApple)); // true
}
}
위 코드를 보면 알 수 있는 건, 두 객체가 다르지만 내용이 같기 때문에 true를 반환하는 것을 확인할 수 있다.
public static void main(String[] args) {
Apple apple1 = new Apple(100);
Apple apple2 = new Apple(100);
Apple apple3 = apple1;
System.out.println(apple1 == apple2); // false
System.out.println(apple1 == apple3); // true
}
위 코드를 보면 알 수 있는 건, 내용이 같더라도 객체가 다르기 때문에 false를 반환하는 것을 알 수 있다.