Post

equals(),hashCode(),==

== 연산자

두 개의 주소가 서로 같은지 비교합니다.

1
2
3
4
5
6
7
8
String str1 = "hello";
String str2 = "hello";
System.out.println(str1 == str2);//true

String str3 = new String("hello");
String str4 = new String("hello");
System.out.println(str3 == str4);//false

equals()

두 개의 값이 서로 같은지 비교합니다.

1
2
3
4
5
6
7
8
String str1 = "hello";
String str2 = "hello";
System.out.println(str1.equals(str2));//true

String str3 = new String("hello");
String str4 = new String("hello");
System.out.println(str3.equals(str4));//true

str1과 str2는 같은 주소를 가리키고 있을 뿐만아니라 내용(값)도 같으므로 equals메서드의 결과 true를 리턴합니다.

str3과 str4는 가리키는 주소는 달라도 내용(값)이 같으므로 equals메서드의 결과 true를 리턴합니다.

하지만 String클래스는 내부적으로 equals메서드를 오버라이드해서 이런 결과가 나타납니다.

String클래스가 아닌 클래스의 객체는 자바가 내용이 같은지 판단하기 어렵습니다.

따라서 equals() 메서드를 오버라이드(재정의)해서 두 객체의 내용이 같은지를 정의해줘야 올바르게 작동합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Person {
    long id; 

    public boolean equals(Object obj) {
        if (!(obj instanceof Person))
            return false;
        
        Person p = (Person)obj;
        
        return id == p.id;
        
    }

    Person(long id) {
        this.id = id;
    }
}

public class equalsOverriding {
    public static void main(String[] args) {
        Person p1 = new Person(8011081111222L);
        Person p2 = new Person(8011081111222L);

        if(p1.equals(p2))
            System.out.println("p1과 p2는 같다");
        else
            System.out.println("p1과 p2는 다르다");
    }
}

p1과 p2는 같다

image

hashCode()

객체의 해쉬코드(hash code)를 반환하는 메서드입니다.

equals()를 오버라이딩하면, hashCode()도 오버라이딩해야합니다.

equals()의 결과가 true인 두 객체의 해시코드는 같아야 하기 때문입니다.

1
2
3
4
5
String str1 = new String("abc");
String str2 = new String("abc");
System.out.println(str1.equals(str2)); // true
System.out.println(str1.hashCode()); // 96354
System.out.println(str2.hashCode()); // 96354
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class Person {
    long id;

    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (!(obj instanceof Person)) {
            return false;
        }

        Person p = (Person) obj;
        return id == p.id;
    }

    public int hashCode() {
        return Long.hashCode(id);
    }

    Person(long id) {
        this.id = id;
    }
}

public class EqualsOverriding {
    public static void main(String[] args) {
        Person p1 = new Person(8011081111222L);
        Person p2 = new Person(8011081111222L);

        if (p1.equals(p2)) {
            System.out.println("p1과 p2는 같다");
        } else {
            System.out.println("p1과 p2는 다르다");
        }

        System.out.println("p1의 해시코드: " + p1.hashCode());
        System.out.println("p2의 해시코드: " + p2.hashCode());
    }
}
p1과 p2는 같다

p1의 해시코드와 ㅔ2의 해시코드가 같다.
This post is licensed under CC BY 4.0 by the author.