상세 컨텐츠

본문 제목

동일성과 동등성

백엔드 공부진행도/Java

by myeongjaechoi 2024. 12. 19. 07:23

본문

equals() vs ==

  • 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
    }
}

위 코드를 보면 알 수 있는 건, 두 객체가 다르지만 내용이 같기 때문에 true를 반환하는 것을 확인할 수 있다.

동일성(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
}

위 코드를 보면 알 수 있는 건, 내용이 같더라도 객체가 다르기 때문에 false를 반환하는 것을 알 수 있다.

 

equals() 사용하는 것이 안전!

'백엔드 공부진행도 > Java' 카테고리의 다른 글

객체 지향  (1) 2024.12.26
자바 프로그램  (1) 2024.12.25
순차 지향 절차지향 객체지향  (0) 2024.12.21
SOLID 원칙  (0) 2024.12.19

관련글 더보기