동일성과 동등성
●동일성과 동등성
●equals()와 ==의 차이
equals()는 객체의 내용을 비교
==는 객체의 참조(레퍼런스)를 비교
두 객체의 내용이 같더라도 서로 다른 객체라면 equals()는 true를 반환할 수 있지만, ==는 false를 반환
●동등성(Equality)
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
}
}
●equals() 메서드를 오버라이딩 한 이유?
public class Object {
...
public boolean equals(Object obj) {
return (this == obj);
}
...
}
●동일성(Identity)
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
}
●String은 객체인데 == 비교해도 되던데 어떻게 된걸까?
public class StringComparison {
public static void main(String[] args) {
String str1 = "안녕하세요";
String str2 = "안녕하세요";
String str3 = new String("안녕하세요");
// 동일성 비교
System.out.println(str1 == str2); // true
System.out.println(str1 == str3); // false
// 동등성 비교
System.out.println(str1.equals(str2)); // true
System.out.println(str1.equals(str3)); // true
}
}
// String.class equals 오버라이딩 되어있음.
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
return (anObject instanceof String aString)
&& (!COMPACT_STRINGS || this.coder == aString.coder)
&& StringLatin1.equals(value, aString.value);
}
●Integer 같은 래퍼 클래스는 어떻게 비교할까?