hashcode
-
이펙티브 자바 - equals & hashcode개발 나누고 더하기/자바, 스프링 2023. 6. 28. 22:29
equals와 hashcode는 루트 클래스인 Object에서 제공하는 오퍼레이션이고 모든 클래스들은 이 두 메서드를 재정의하지 않는 이상 Object에 정의되어 있는대로 쓰게 된다. 실무에서는 주로 식별자로 두 객체가 동일한지 비교하고 가끔 값 객체 비교에 써서 equals를 직접 구현했던 일이 적었다. HashMap, HashSet에 key로 enum이나 Integer, String같은 기본 랩퍼 클래스를 써서 hashcode는 볼일이 거의 없었지만 이 기회에 다시 한번 짚어보는것도 좋을 것 같다. equals는 일반 규약을 지켜 재정의하라 equals 메서드는 재정의하기 쉬워 보이지만 곳곳에 함정이 도사리고 있어서 자칫하면 끔찍한 결과를 초래한다. 문제를 회피하는 가장 쉬운 길은 아예 재정의하지 않..