public class Student {
String name;
String number;
int birthYear;
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "홍길동";
s1.number = "1234";
s1.birthYear = 1995;
Student s2 = new Student();
s2.name = "홍길동";
s2.number = "1234";
s2.birthYear = 1995;
if(s1.equals(s2))
System.out.println("s1==s2");
else
System.out.println("s1 != s2");
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s1);
}
}
s1 != s2
1915910607
284720968
Student@170861
s1과 s2는 같은 값을 가지고 있는데도 불구하고, 다른 결과와, 해시코드 값을 출력한다.
이유는 equals, hashCode 메서드가 Object 클래스의 메소드를 사용하고 있기 때문이다.
또한 s1의 속성값이 출력되지 않고 객체의 주소값을 출력하고 있다.
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return Objects.equals(number, student.number);
}
number만 같다면 같다고 나오도록 오버라이딩 하였다.
s1==s2
1509473
1509473
equals()메서드와 hashCode()메서드가 오버라이딩 되어 원하는 결과를 출력하였다.
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Student{");
sb.append("name='").append(name).append('\'');
sb.append(", number='").append(number).append('\'');
sb.append(", birthYear=").append(birthYear);
sb.append('}');
return sb.toString();
}
Student{name='홍길동', number='1234', birthYear=1995}
오버라이딩 한대로 출력된다.
Integer i3 = 5;//Integer i3 = new Integer(5);
기본형 타입의 int가 자동으로 객체타입의 Integer로 변환되는것을 뜻함
int i4 = i3; // int i4 = i3.intValue();
반대로 객체타입의 Integer가 기본형 타입의 int로 변환되는것을 뜻한다.