[Java] hashCode(), toString()
hashCode() 메서드
해싱(hashing) 기법에 사용되는 해시함수를 구현한 것이다.
해싱은 데이터 관리법 중의 하나이다.
객체의 해쉬 코드를 반환하는 메서드이며, 반환된 데이터 타입은 int형이다.
public class inheritance {
public static void main(String[] args) {
String str1="ABC";
String str2="ABC";
System.out.println(str1.equals(str2));
System.out.println(str1.hashCode());
System.out.println(str2.hashCode());
System.out.println(System.identityHashCode(str1));
System.out.println(System.identityHashCode(str2));
}
}
true
75439
75439
1586600255
1586600255
String 클래스는 문자열의 내용이 같으면, 동일한 해시 코드를 반환하도록 hasCode() 메서드가 오버 라이딩되어 있다.
equals()를 오버 라이딩하면, hasCode()도 오버라이딩해야 한다.
equals()의 결과가 true인 두 객체의 해시 코드는 같아야 하기 때문이다.
System.identityHashCode()는 객체마다 다른 해시 코드를 반환하는 메서드이다. Object클래스의 hashCode()와 동일하다.
하지만, 위에 hashCode()와 System.identityHashCode()의 반환 값이 다른 이유는 hashCode는 오버라이딩이 되어 서로 같은 값을(str1==str2) 반환하는 것이다.
참고로 32bit JVM은 주소 값이 int형이고 64bit JVM은 주소값이 long형이라 주소값이 겹치는 경우가 발생할 수 있다.
사실상 hashCode메서드는 long타입으로 바뀌어야 하지만, 기존에 많이 사용되는 메서드라 바꾸기에 어려워 아직까지 int형인 것이다. (System.identityHashCode() 값이 같은 이유)
그리고, equals() 메서드를 오버 라이딩하여 ture값을 유도했으면 hasCode()도 오버라이딩을 해야 한다.
toString() 메서드
public String toString() {
return getClass().getName()+"@"+Integer.toHexString(hashCode());
}
기본적인 toString메서드의 내용은 다음과 같다.
public class langTest {
public static void main(String[] args) {
System.out.println(new ToStringTest().toString());
System.out.println(new ToStringTest("test2",2).toString());
}
}
class ToStringTest{
String str;
int i;
ToStringTest(){
this("test1",1);
}
ToStringTest(String str,int i){
this.str=str;
this.i=i;
}
}
ToStringTest@1c4af82c
ToStringTest@379619aa
toString메서드를 오버 라이딩 없이 사용하면 위에 toString메서드 내용처럼 class네임+"@"+객체 주소를 16진수로 반환한다.
public class langTest {
public static void main(String[] args) {
System.out.println(new ToStringTest().toString());
System.out.println(new ToStringTest("test2",2).toString());
}
}
class ToStringTest{
String str;
int i;
ToStringTest(){
this("test1",1);
}
ToStringTest(String str,int i){
this.str=str;
this.i=i;
}
public String toString() { //오버라이딩
return str+" "+i;
}
}
test1 1
test2 2
toString메서드를 오버라이딩하여 toStringTest클래스의 인스턴스 변수 str과 i의 값을 출력하게 한다.
🎈 지금까지 배운 내용 복습 코드
import java.util.Objects;
public class Main {
public static void main(String[] args) {
ExClass exc1 = new ExClass("길동", 25);
ExClass exc2 = new ExClass();
exc2.name = "길동";
exc2.age = 25;
System.out.println(exc1.toString());
System.out.println(exc2);
System.out.println(exc1.equals(exc2));
System.out.println(exc1.hashCode() + " " + exc2.hashCode());
System.out.println(System.identityHashCode(exc1)+" "+System.identityHashCode(exc2));
}
}
class ExClass {
String name;
int age;
ExClass() {
}
ExClass(String name, int age) {
this.name = name;
this.age = age;
}
// toString() 오버라이딩
public String toString() {
return "name:" + name + ", " + "age:" + age;
}
// equals() 오버라이딩
public boolean equals(Object obj) {
ExClass ec;
if (obj instanceof ExClass) {
ec = (ExClass) obj;
return this.name.equals(ec.name) && this.age == ec.age;
} else
return false;
}
// equals()를 오버라이딩을 하면 hasCode()도 오버라이딩 해야한다.
public int hashCode() {
return Objects.hash(name, age); // 가변인자라 매개변수 제한이 없다.
}
}
name:길동, age:25
name:길동, age:25
true
44288857 44288857
474675244 932583850
실행결과