객체의 주소값 비교 메소드 System.identityHashCode Object.hashCode 본문

java

객체의 주소값 비교 메소드 System.identityHashCode Object.hashCode

violet4795 2019. 1. 10. 11:18

모든 Object에 작성되어 오버라이드 되는 hashCode와 System.identityHashCode는 서로 역할이 같다.


java8 api




hashCode

public int hashCode()
Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by HashMap.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.)

Returns:
a hash code value for this object.
See Also:
equals(java.lang.Object)System.identityHashCode(java.lang.Object)


identityHashCode

public static int identityHashCode(Object x)
Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode(). The hash code for the null reference is zero.
Parameters:
x - object for which the hashCode is to be calculated
Returns:
the hashCode
Since:
JDK1.1


identityHashCode 메소드의 description에도 hashCode가 오버라이딩 된것과 상관없이 객체주소에 따른 해시코드를 반환해준다고 기술되어있다.

기본적으로 hashCode는 객체의 주소에 해시를 적용하여 해시코드를 반환하지만 객체에 오버라이딩 되는경우 그 객체에서 선언된 내용으로 작동한다.


ex) String의 경우 해당 객체의 주소가 아닌 객체가 가진 문자열로 hashCode를 생성한다.


System.identityHashCode는 오로지 객체의 주소값을 이용하여 hashCode를 생성한다는 차이점이 있다.



추울처 : https://docs.oracle.com/javase/8/docs/api/

'java' 카테고리의 다른 글

illegal group reference  (0) 2019.08.13
Java 심화  (0) 2019.05.25
java reflection  (0) 2018.11.30