새로운 객체를 할당하고 이를 다른 참조변수에 복사하는 경우에 대해 알아본다.
결과적으로는 참조변수에 기존의 객체를 참조하는 참조변수를 대입하면 그 두 변수는 동일한 것을 가리킨다.
그리고 값이 똑같다고 객체까지 같다고 할 수는 없다.
public class ObjectTest {
int data;
public ObjectTest(int x) {
data = x;
}
public ObjectTest clone() throws CloneNotSupportedException {
ObjectTest temp = new ObjectTest(this.data);
return temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ObjectTest obj1 = new ObjectTest(10);
ObjectTest obj2 = obj1;
ObjectTest obj3 = new ObjectTest(10);
ObjectTest obj4;
try {
obj4 = obj3.clone();
} catch (CloneNotSupportedException e) {
obj4 = null;
System.out.println("복제할 객체가 없습니다.");
}
int i = 10;
int j = 10;
if (i == j) {
System.out.println("i와 j의 값은 같습니다.");
}
if (obj1 == obj2)
System.out.println("obj1과 obj2의 위치는 같습니다.");
else
System.out.println("obj1과 obj2의 위치는 다릅니다.");
if (obj4 == obj3)
System.out.println("obj4과 obj3의 위치는 같습니다.");
else
System.out.println("obj4과 obj3의 위치는 다릅니다.");
if (obj1.equals(obj2))
System.out.println("obj1과 obj2의 내용은 같습니다.");
else
System.out.println("obj1과 obj2의 내용은 다릅니다.");
if (obj4.equals(obj3))
System.out.println("obj4과 obj3의 내용은 같습니다.");
else
System.out.println("obj4과 obj3의 내용은 다릅니다.");
System.out.println("obj1 이름은 " + obj1.toString());
System.out.println("obj1 해시코드 =" + obj1.hashCode());
System.out.println("obj2 해시코드 =" + obj2.hashCode());
System.out.println("obj3 해시코드 =" + obj3.hashCode());
System.out.println("obj4 해시코드 =" + obj4.hashCode());
}
}
결과 :
i와 j의 값은 같습니다.
obj1과 obj2의 위치는 같습니다.
obj4과 obj3의 위치는 다릅니다.
obj1과 obj2의 내용은 같습니다.
obj4과 obj3의 내용은 다릅니다.
obj1 이름은 ObjectTest@47415dbf
obj1 해시코드 =1195466175
obj2 해시코드 =1195466175
obj3 해시코드 =343001893
obj4 해시코드 =986707103