Java에서 객체의 메모리 주소를 직접 확인하는 것은 언어 자체에서는 제공하지 않는 기능이다.
> 그러나, 객체의 해시 코드(hash code)를 통해 간접적으로 객체를 식별할 수 있다. 해시 코드는 객체의 메모리 주소와 관련이 있지만, 직접적으로 메모리 주소를 나타내지는 않는다.
객체의 해시 코드 확인
System.identityHashCode(Object x) 메서드는 객체의 해시 코드를 반환한다. 이 값은 객체의 메모리 주소와 밀접한 관련이 있지만, 직접적인 메모리 주소는 아니라고 볼 수 있다. 그래도 이를 통해 두 객체가 동일한지 여부를 간접적으로 확인이 가능하다.
System.out.println("### dto.getCreatedById() hash code: " + System.identityHashCode(dto.getCreatedById()));
System.out.println("### memberDto.getMemberId() hash code: " + System.identityHashCode(memberDto.getMemberId()));
- 예제 -
public class Main {
public static void main(String[] args) {
String str1 = new String("hello");
String str2 = new String("hello");
// 해시 코드 출력
System.out.println("str1 hash code: " + System.identityHashCode(str1));
System.out.println("str2 hash code: " + System.identityHashCode(str2));
// getClass()로 타입 확인
System.out.println("str1 type: " + str1.getClass());
System.out.println("str2 type: " + str2.getClass());
}
}
출력결과
str1 hash code: 12345678
str2 hash code: 87654321
str1 type: class java.lang.String
str2 type: class java.lang.String
> 이 예제에서 System.identityHashCode를 사용하여 str1과 str2의 해시 코드를 출력하는데 두 해시 코드가 다르므로 str1과 str2는 서로 다른 객체임을 알 수 있다.
주의사항
- 해시 코드는 메모리 주소와 밀접한 관련이 있지만, 직접적인 메모리 주소는 X
- 두 객체가 동일한 해시 코드를 가질 수 있습니다. 이는 해시 충돌이라고 하며, 두 객체가 동일한 객체임을 보장하지 X
- 객체의 동등성을 비교할 때는 해시 코드보다는 equals 메서드를 사용하는 것이 좋다.
따라서 객체의 타입을 확인하고 싶다면 getClass()를 사용하고, 객체의 식별자를 확인하고 싶다면 System.identityHashCode를 사용할 수 있다. 그러나 메모리 주소를 직접 확인하는 것은 자바에서 지원하지 않는다.
'Develop > Java' 카테고리의 다른 글
게시판 상세페이지에서 이전글, 다음글 구현하기 (0) | 2024.07.02 |
---|---|
[Thymeleaf] temporals.format 으로 날짜 설정하기 (0) | 2024.06.28 |
상시 게시글을 리스트의 상단으로 올리기 (0) | 2024.06.20 |
@Valid 어노테이션에 대해서 (0) | 2024.06.17 |
String 값을 equals를 사용하여 비교하기 ('=='를 쓰지 않는 이유) (0) | 2024.06.17 |