set of black teaspoons on beige surface

객체가 같다는 것

제공

레퍼런스 동치
  • 동일한 오브젝트를 참조하는 녀석들은 완전한 동치
  • hashCode 도 당연히 같음
객체 동치
  • 서로 다른 오브젝트가 같다고 말할 수 있는 경우
  • hashCode() 함수와 equals() 함수를 overriding 해서 구현해야 함
  • 서로 다른 객체의 hashCode 가 일치해야 하고, equals 함수도 True여야 함(A.equals(B)도 True, B.equals(A)도 True)
  • equals 함수가 True이면 두 객체의 hashCode 가 같지만, hashCode 가 같다고 equals가 반드시 True는 아님

◼︎ 객체 동치는 왜 쓰는걸까? Value Object를 만들기 위해서 쓴다.

Value Object
A small simple object, like money or a date range, whose equality isn’t based on identity.(객체 동치를 쓴다는 얘기)
http://martinfowler.com/eaaCatalog/valueObject.html

◼︎ hashCode가 같으면 객체 동치가 성립하는 것이 아닌가? 아니다.

hashCode는 객체의 힙 메모리를 기준으로 hash 알고리즘에 따라 만들어 진다. 따라서 서로 다른 객체가 같은 hashCode를 가질 수 있다.
http://jnylove.tistory.com/182

◼︎ 테스트 코드 (http://stackoverflow.com/a/9662078)

public static void testEquality(){
    String str1 = “Hello world.”;
    String str2 = “Hello world.”;

    if (str1 == str2)
        System.out.print(“str1 == str2\n”);
    else
        System.out.print(“str1 != str2\n”);

    if(str1.equals(str2))
        System.out.print(“str1 equals to str2\n”);
    else
        System.out.print(“str1 doesn’t equal to str2\n”);

    String str3 = new String(“Hello world.”);
    String str4 = new String(“Hello world.”);

    if (str3 == str4)
        System.out.print(“str3 == str4\n”);
    else
        System.out.print(“str3 != str4\n”);

    if(str3.equals(str4))
        System.out.print(“str3 equals to str4\n”);
    else
        System.out.print(“str3 doesn’t equal to str4\n”);
}

◼︎ Value Object 와 Reference Object

프로그램을 가장 훌륭하게 작성하는 방법은 상태가 변경되는 오브젝트들과 수학적인 값을 나타내는 오브젝트들의 조합으로 표현하는 것이다. – Kent Beck
여기에 있는 4개의 글 추천 http://aeternum.egloos.com/1105776


코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다