본문 바로가기
study/Java

[Java] 29. 기본 API (hashCode)

by 금이패런츠 2022. 3. 25.
728x90
반응형
package chap11;
/*
 * hashCode() : 원래의 의미는 객체를 구분하기 위한 참조값
 *              내용 비교를 위해서 hashCod 메서드를 오버라이딩함(권장).
 * 자바에서 논리적 동등성 비교를 위해 equals 메서드와 hashCode 메서드를 이용함.    
 * => equals 메서드 오버라이딩시 hashCode 메서드도 함께 오버라이딩 하도록 권장함.         
 */
public class HashCodeEx1 {
	public static void main(String[] args) {
		Equal e1 = new Equal(10);
		Equal e2 = new Equal(10);
		System.out.println(e1.hashCode());
		System.out.println(e2.hashCode());
		System.out.println(System.identityHashCode(e1)); //실제 hashCode값
		System.out.println(System.identityHashCode(e2)); //실제 hashCode값
		
		String s1 = new String("abc");
		String s2 = new String("abc");
		System.out.println(s1.hashCode()); //내용비교를 위해서 오버라이딩 됨
		System.out.println(s2.hashCode());
		System.out.println(System.identityHashCode(s1)); //실제 hashCode값
		System.out.println(System.identityHashCode(s2)); //실제 hashCode값
		if(s1 != s2) System.out.println("s1 != s2: s1객체와 s2객체는 다른 객체임");
		if(s1.equals(s2)) System.out.println("s1.equals(s2): s1객체와 s2객체는 같은 내용의 객체임");
	}
}
728x90
반응형