JAVA의 다양한 클래스
@Override
public String toString() {
return title+","+author;
}
hashCode()는 인스턴스의 저장 주소를 반환함
힙메모리에 인스턴스가 저장되는 방식이 hash 방식 => JVM에서 힙 메모리를 관리하는 방식이 Hash 방식
hash : 정보를 저장, 검색하는 자료구조 -> hash(key) = index
자료의 특정 값(키 값)에 대한 저장 위치를 반환해주는 해시 함수를 사용
두 인스턴스가 같다는 것은?
-두 인스턴스에 대한 equals()의 반환 값이 true
-동일한 hashCode() 값을 반환
논리적으로 동일함을 위해 equals() 메서드를 재정의 하였다면 hashCode()메서드도 재정의 하여 동일한 hashCode 값이 반환되도록 한다
equals(),hashcode() override 예시
@Override
public boolean equals(Object obj) {
if(obj instanceof Student){
Student std = (Student) obj;
if(this.studentNum == std.studentNum)
return true;
else return false;
}
return false;
}
@Override
public int hashCode() {
return studentNum;
}
public class EqualsTest {
public static void main(String[] args) throws CloneNotSupportedException {
Student std1 = new Student(100,"Lee");
Student copyStudent = (Student)std1.clone(); //이렇게 하면 컴파일 에러!!
}
}
@Override
public Object clone() throws CloneNotSupportedException {
Object obj = null;
try{
obj = super.clone();
}catch(CloneNotSupportedException e){
}
return obj;
}
@Override
public Student clone() throws CloneNotSupportedException {
Object obj = null;
try{
obj = super.clone();
}catch(CloneNotSupportedException e){
}
return (Student) obj; //downcasting
}
public class Student implements Cloneable{
}