※ hash code : 각 객체의 주소값을 변환하여
생성한 고유한 정수값.
두 객체가 동일한 객체인지 비교할 때 사용.
equals() 비교에 사용되는 내용의 변경이 없다면, 그 어플리케이션이 실행되는 동안, hash code메서드가 반환하는 값에 변화는 없다.
equals(Object) 비교에서 비교한 두 객체가 같다고 판단되었으면,
두 객체의 hash code메서드는 동일값을 반환한다.
equals(Object) 비교에서 두 객체가 다르다고 판단되었더라도,
두 객체의 hash code메서드가 반드시 다른 값을 반환할 필요는 없다. 하지만, hash table의 성능을 높이기 위해서, 다른 두 객체가 다른 값을 반환하게 하는 것이 좋다.
※ 객체 간의 구별을 위해 중복값을 피한 해시 코드 작성 예 :
public class User {
private long id;
private String name;
private String email;
@Override
public int hashCode() {
return (int) id *
name.hashCode() *
email.hashCode();
}
}
※ 표준적인 hashCode() 예 :
public class User {
private Long id;
private String name;
private String email;
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + (int) id;
hash = 31 * hash + (name == null ?
0 : name.hashCode() );
hash = 31 * hash + (email == null ?
0 : email.hashCode() );
return hash;
}
}
※ Intelli J 에서 해시 코드 작성 예 :
Objects.hash(name, email)
※ 충돌 방지를 위한 해시코드 예 :
import java.util.Objects;
public class User {
private long id;
private String name;
private String email;
public User(long id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
public int hashCode() {
int hash = 7;
hash = 31 * hash + (int) id;
hash = 31 * hash + (name == null ? 0 : name.hashCode());
hash = 31 * hash + (email == null ? 0 : email.hashCode());
System.out.println("hashCode() called - Computed hash: " + hash);
return hash;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return id == user.id &&
Objects.equals(name, user.name) &&
Objects.equals(email, user.email);
}
}
※ 해시맵에 저장 후, containsKey() 메서드로 포함되어 있는지, 찾는 예제 :
import java.util.HashMap;
import java.util.Map;
public class Application {
public static void main(String[] args) {
Map<User, User> users = new HashMap<>();
User user1 = new User(1L, "Gyunny", "Gyunny@naver.com");
User user2 = new User(2L, "Hyungil", "Hyungil@naver.com");
User user3 = new User(3L, "Bobae", "Bobae@naver.com");
users.put(user1, user1);
users.put(user2, user2);
users.put(user3, user3);
if (users.containsKey(user1)) {
System.out.print("User found in the collection");
}
}
}