본문 바로가기
JAVA/자바의 클래스

hashCode() 메서드 - Object클래스의 메서드

by 김꾸꾸(하트) 2022. 11. 17.

해시(Hash) → 자료구조

정의

정보를 저장하거나 검색할 때 사용하는 자료구조

 

특징

힙메모리에 인스턴스가 저장되는 방식이 hash 방식

 

사용법

해시함수를 사용하여 정보를 저장하거나 가져오거나 함.

 

 

 

해시함수 → 위치를 제공

정의

객체의 특정정보(key값)를 매게변수 값으로 넣으면

그 객체가 저장되어야 할 위치나 저장된 해시 테이블 주소(위치)를 제공

 

특징

객체의 정보를 알면 해당 객체의 위치를 빠르게 검색 가능

 

 

 

hashcode() 메서드 → 해시 코드값을 제공

정의) 인스턴스의 주소값인 해시 코드값을 을 제공하는 메서드

getClass().getName() @ Integer.toHexString(hashCode()) 
 = 클래스명 @ 해시코드 값( = 자바 가상머신이 힙메모리에 저장한 '인스턴스 주소값')

 

 

 

 

인스턴스의 논리적 동일성

  • 논리적으로 동일함을 위해
  • 주소값을 비교하는 equals() 메서드를 재정의 하였다면

        주소값을 제공하는 hashCode()메서드도 재정의 하여

        동일한 hashCode 값이 반환되도록 한다

 

 

실제 메모리 주소값 출력법

System.identityHashCode(참조변수)

hashCode() 메서드hashCode() 메서드 예제

Student.java

public class Student {

  //멤버변수
	private int studentId;
	private String studentName;

	
	//생성자
	public Student(int studentId, String studentName)
	{
		this.studentId = studentId;
		this.studentName = studentName;
	}
	
	//주소값 비교하는 equals()메서드 재정의
	**public boolean equals(Object obj) {
		if( obj instanceof Student) {
			Student std = (Student)obj;
			if(this.studentId == std.studentId )
				return true;
			else return false;
		}
		return false;
		
	}**
	
	//주소값 제공하는 hashCode()메서드 재정의
	**@Override// 재정의 가능
	public int hashCode() {
		return studentId;
	}
}**

EqualTest.java

public class EqualTest {
public static void main(String[] args) {
	Student Lee = new Student(100, "Lee");
	Student Lee2 = Lee;
	Student Shun = new Student(100, "Lee");

	System.out.println(Lee == Shun);
	System.out.println(Lee.equals(Shun));

	System.out.println(Lee.hashCode());
	System.out.println(Shun.hashCode());

	Integer i1 = new Integer(100);
	Integer i2 = new Integer(100);

	System.out.println(i1.equals(i2));
	System.out.println(i1.hashCode());
	System.out.println(i2.hashCode());

	System.out.println(System.identityHashCode(i1));
	System.out.println(System.identityHashCode(i2));

}
}

 

 

 

 

 

 

 

출처 - Do it! 자바 프로그래밍 입문 (박은종 선생님)

https://www.aladin.co.kr/shop/wproduct.aspx?ItemId=157852460 

'JAVA > 자바의 클래스' 카테고리의 다른 글

Class클래스- 정보가져오기  (0) 2022.11.21
String클래스  (0) 2022.11.19
clone()메서드 - Object클래스의 메서드  (0) 2022.11.18
equals()-Object클래스의 메서드  (0) 2022.11.16
Object 클래스  (0) 2022.11.15