Java

[JAVA] 객체 주소값 확인하기

YEJI ⍢ 2022. 12. 24. 20:29
728x90

객체의 주소를 확인하기 위해 우리는 hashcode() 함수를 사용할 수 있습니다.

주소값은 중요하기 때문에 Hashcode는 실제 메모리 주소가 아닌 메모리 주소 값에 해싱된 값을 return 해줍니다.

- 두 객체의 hashcode가 다르면 두 객체가 같지 않음을 나타냅니다.

- 두 객체의 hashcode가 같으면 두 객체가 같거나 다를 수 있음을 나타냅니다.

 

 

객체의 주소값이 같은지 확인하고 싶을 때 자바에서는 "==" operator을 사용합니다.

기본적으로 우리가 아는 "=="의 역할은 어떤 두 개의 값이 같은지 확인하는 용도였을 것입니다.

 

그럼 자바에서 두 개의 값이 같은지 확인하는 용도는 어떻게 할까요?

equals()라는 함수를 사용합니다.

 

 

아래 예제를 통해 더 잘 살펴봅시다.

public static void main(String[] args) {
	String word1 = new String("Hello");
	String word2 = new String("Hello");
	
	
	System.out.println(word1.hashCode());
	System.out.println(word2.hashCode());
	System.out.println(word1 == word2);
	System.out.println(word1.equals(word2));
}

word1과 word2의 hashCode는 동일합니다.

하지만 주소값을 비교해보면 동일하지 않음을 알 수 있습니다.

마지막으로 두 개의 문자열이 일치하는지 확인하기 위해 equals 함수를 사용했고

두 개의 문자열이 같다는 것을 확인할 수 있습니다.

 

 

public static void main(String[] args) {
	String word1 = new String("Hi");
	String word2 = new String("Hello");
	
	
	System.out.println(word1.hashCode());
	System.out.println(word2.hashCode());
	System.out.println(word1 == word2);
	System.out.println(word1.equals(word2));
}

word1과 word2의 value가 다르기 때문에 hashCode, address, value 모두 다릅니다.

 

 

 

◡̈