Programming/JAVA
[JAVA] HashCode
Plone
2020. 9. 12. 20:55
package Study;
public class HashCodeStudy {
public static void main(String[] args) {
/*HashCode : 객체의 주소를 기반으로 생성되는 정수 값 */
HashCodeStudy study1 = new HashCodeStudy();
HashCodeStudy study2 = new HashCodeStudy();
HashCodeStudy study3 = study2;//study2라는 객체를 생성할 때 사용 된 주소가 study3에 그대로 사용 됨
System.out.println("study1 : " + study1.hashCode());//키 : 366712642 값 : study1
System.out.println("study2 : " + study2.hashCode());//키 : 1829164700 값 : study2
System.out.println("study3 : " + study3.hashCode());//키 : 1829164700 값 : study2
/*String 클래스에 한해서는 고유의 값이 아님*/
String str1 = "ABC123";
String str2 = "ABC123";
String str3 = "DEF456";
System.out.println(str1.hashCode());//키 : 1923891888 값 : ABC123
System.out.println(str2.hashCode());//키 : 1923891888 값 : ABC123
System.out.println(str3.hashCode());//키 : 2012642256 값 : DEF456
}
}
해시코드(HashCode)란 객체가 생성될 때 사용된 주소를 기반으로 생성되는 정수 값이다
study1과 study2는 같은 클래스를 이용해 객체를 생성했어도 생성 주기가 다르기 때문에 해시코드도 다르다
하지만 study3는 이미 생성된 study2를 기반으로 생성되었기 때문에 해시코드 값이 동일하다
또한 String 클래스에 한해서는 객체가 생성될때 사용된 주소가 아닌 문자열을 기반으로 정수 값이 생성된다
즉, 중복된 해시코드가 존재할 가능성이 있다
해시코드를 고유값으로 처리하는 건 보지 못했다