본문 바로가기

자바(JAVA)
[자바(Java)] equals , hashcode

//equals() / hashCode()

- equals()와 hashCode() 는 함께 실행되어야 한다.

- hashCode() : 객체들을 똑같이 나누어 다른 bucket에 담아준다.
    ~ 두 객체가 정확히 일치한다면, 그 둘의 hashCode 또한 정확하게 같아야 한다.
    ~ 객체의 값이 변하지 않는 이상 hashCode 값은 절대 변해서는 안 된다.


package com.sorrel012.tips.eclipse;

class Client {
	
	private int id;
	
	public Client(int id) {
		super();
		this.id = id;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		return result;
	}

	@Override
	public boolean equals(Object that) {
		if (this == that) {
			return true;
		}
		if (that == null) {
			return false;
		}
		if (getClass() != that.getClass()) {
			return false;
		}
		Client other = (Client) that;
		if (id != other.id) {
			return false;
		}
		return true;
	}

}

public class EqualsRunner {

	public static void main(String[] args) {

		Client c1 = new Client(1);
		Client c2 = new Client(1);
		Client c3 = new Client(2);
		System.out.println(c1.equals(c2));
		System.out.println(c1.equals(c3));

	} //main
	
}

'자바(JAVA)' 카테고리의 다른 글

[자바(Java)] Collection 총 정리  (0) 2023.02.28
[자바(Java)] static  (0) 2023.02.20
[자바(Java)] 동기화  (0) 2023.02.19
[자바(Java)] 디버그(debug)  (0) 2023.02.09
[자바(Java)] 연산자  (0) 2023.02.06