HashMap 자료구조에서 Key 로 객체를 활용하면??
public class SampleClass {
private int code;
public SampleClass(int code){
this.code = code;
}
public int getCode() {
return code;
}
}
위와 같은 샘플 클래스를 만들고
SampleClass sample1 = new SampleClass(1);
SampleClass sample2 = new SampleClass(2);
SampleClass sample3 = new SampleClass(1);
HashMap<SampleClass, String> map = new HashMap<>();
map.put(sample1, "first");
map.put(sample2, "second");
map.put(sample3, "third");
map.forEach(
(key, value) -> {System.out.println(key+", "+value+", "+key.getCode());}
);
나는 sample1 과 sample3 가 같음을 의도했지만
SampleClass@41629346, first, 1
SampleClass@6d311334, third, 1
SampleClass@404b9385, second, 2
결과는 이렇게 출력
왜냐? sample1 과 sample3 내부의 값이 같다고 같은 객체가 아니기 때문
객체가 참조되는 메모리의 주소가 서로 다르기때문에 다른 Key 값으로 인식
그럼 의도대로 동작하게 하려면?
!! equals, hashcode 메소드를 재정의 !!
equals 메소드
동일성 비교
객체 인스턴스의 주소 값을 비교
hashcode 메소드
동등성 비교
equals 메소드를 이용해 객체 내부의 값을 비교
public class SampleClass {
private int code;
public SampleClass(int code){
this.code = code;
}
public int getCode() {
return code;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SampleClass that = (SampleClass) o;
return code == that.code;
}
@Override
public int hashCode() {
return Objects.hash(code);
}
}
equlas 메소드는
내부 값(code) 을 비교하여 두 객체가 동등한지, 아닌지 판단하도록 구현
hashcode 메소드는
내부 값(code) 이 같다면 동일한 hash 값을 반환하도록 구현
이로써 내가 원하는
내부 값이 같으면 같은 객체다
라는 동작이 구현 가능해진다
SampleClass@20, third, 1
SampleClass@21, second, 2
이렇게 sample1 과 sample3 가 동일한 객체, Key 로 판단되어 값이 변화하게 된다
'끄적 > ?' 카테고리의 다른 글
Design Patten (0) | 2023.09.19 |
---|---|
업캐스팅 다운캐스팅 (0) | 2023.08.27 |
Generic (0) | 2023.08.27 |
Java ArrayList와 List 차이 (0) | 2023.08.27 |
String, StringBuffer, StringBuilder (0) | 2023.08.27 |