카테고리 없음
자바의 클래스들 2. Object 클래스의 메서드 활용
코딩펭귄
2023. 12. 19. 18:08
equals() 메서드
- 두 인스턴스의 주소 값을 비교하여 true/false를 반환
- 재정의 하여 두 인스턴스가 논리적으로 동일함의 여부를 구현함
- 인스턴스가 다르더라도 주소값(hash code 값이 반환하는 값)이 논리적으로 동일한 경우 true를 반환하도록 재정의 할 수 있음
- ex) 같은 학번, 같은 사번, 같은 아이디의 회원...
equals()와 hashCode()는 페어임. equals를 오버라이딩하면, 그개체가 반환하는 hash값도 오버라이딩 해줘야함
hashCode() 메서드
- hashCode()는 인스턴스의 저장 주소를 반환함. (int 값으로 반환)
- 힙메모리에 인스턴스가 저장되는 방식이 hash 방식
- hash : 정보를 저장, 검색하는 자료구조
- 자료의 특정 값(키 값)에 대한 저장 위치를 반환해주는 해시 함수를 사용
- 두 인스턴스가 같다는 것은 : 두 인스턴스에 대한 equals()의 반환 값이 true 동일한 hashCode() 값을 반환
- 논리적으로 동일함을 위해 equals() 메서드를 재정의 하였다면 hashCode()메서드도 재정의 하여 동일한 hashCode 값이 반환되도록 함
public class Student implements Cloneable {
private int studentNum;
private String studentName;
public void setStudentName(String name) {
this.studentName = name;
}
public Student(int studentNum, String studentName) {
this.studentNum = studentNum;
this.studentName = studentName;
}
public String toString(){
return studentNum +","+ studentName;
}
//논리적으로 같음을 보이기 위한 equals(), hashcode() 오버라이딩
@Override
public boolean equals(Object obj) {
if(obj instanceof Student) { //obj가 student면 Student로 변환
Student std = (Student)obj; // student로 obj를 다운캐스팅
if(this.studentNum == std.studentNum)
return true;
else return false;
}
return false;
}
@Override
public int hashCode() {
// 학번이 같을때 같은학번 반환
return studentNum; //equals()할때 썼던 멤버변수 studentNum 사용하면됨!
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
}
public class EqualTest {
public static void main(String[] args) throws CloneNotSupportedException {
Student std1 = new Student(100, "Lee");
Student std2 = new Student(100, "Lee");
Student std3 = std1; // 주소값만 복사해준것 (=std1, std2와 주소값 동일함)
System.out.println(std1 == std2); // false
System.out.println(std1.equals(std2)); //false, 오버라이드 이후에는: 주소는 다르지만, 논리적으로는 동일하므로 true(100=100)
System.out.println(std1.hashCode()); //617901222
System.out.println(std2.hashCode()); // 1159190947
System.out.println(System.identityHashCode(std1)); //실제 HashCode값 : 617901222
System.out.println(System.identityHashCode(std2)); //실제 HashCode값 : 1159190947
String str1 = new String("abc");
String str2 = new String("abc");
System.out.println(str1.equals(str2)); //true
System.out.println(str1.hashCode()); //96354
System.out.println(str2.hashCode()); //96354
//Int는 new하지 않아도 됨
Integer i = 100;
System.out.println(i.hashCode()); //100
Student copyStudent = (Student)std1.clone(); //clone의 리턴타입은 object이지만, student로 캐스팅해줌
System.out.println(copyStudent); //100,Lee
std1.setStudentName("Kim");
Student copyStudent1 = (Student)std1.clone();
System.out.println(copyStudent1); //100,Lee -> 100,Kim
}
}
clone() 메서드
- 객체의 원본을 (변화된 상태 포함)그대로 복제하는데 사용하는 메서드
- '생성'하는것이 아닌, 인스턴스의 상태를(하위클래스까지) 그대로 복제하는것
- 생성과정의 복잡한 과정을 반복하지 않고 복제 할 수 있음
- clone()메서드를 사용하면 객체의 정보(멤버 변수 값등...)가 동일한 또 다른 인스턴스가 생성되는 것이므로, 객체 지향 프로그램에서의 정보 은닉, 객체 보호의 관점에서 위배될 수 있음
- 해당 클래스의 clone() 메서드의 사용을 허용한다는 의미로 cloneable 인터페이스를 명시해 줌
public class Student implements Cloneable{ .......