Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

Super Coding Addict

Ch10. 자바 기본 클래스 (2) - Object 클래스 본문

JAVA 문법

Ch10. 자바 기본 클래스 (2) - Object 클래스

밍응애 2021. 3. 1. 13:40

*  equals()메서드

- 두 객체의 동일함을 논리적으로 재정의 할 수 있음

  • 물리적 동일함 : 같은 메모리 주소를 가지는 객체
  • 논리적 동일함 : 같은 학번의 학생 등처럼 논리적으로는 동일한 객체

=> 물리적으로는 다른 메모리에 위치한 객체이더라도, 논리적으로는 동일함을 구현하기 위해 사용하는 메서드

 

- 예제

# EquaslTest 클래스

package ch10.object;

public class EqualsTest {

	public static void main(String[] args) {
		String str1 = new String("abc");
		String str2 = new String("abc");

		System.out.println(str1 == str2);	//메모리 주소 비교
		System.out.println(str1.equals(str2));	//문자열 비교
	}

}

--> 메모리 주소를 비교하면 false

--> 문자열 비교를 하면 true

--> 원래 Object의 equals()메서드는 메모리 주소를 비교하는 것이나, String클래스에서 문자열비교를 하는 것으로 재정의를 하였음 

=> class의 목적에 맞게 equals()메서드를 재정의해서 씀

 

- 예제

package ch10.object;

class Student{
	int studentNum;
	String studentName;
	
	public Student(int studentNum, String studentName) {
		this.studentNum = studentNum;
		this.studentName = studentName;
	}

	@Override
	public boolean equals(Object obj) {
		if( obj instanceof Student) {
			Student std = (Student)obj; //다운캐스팅
			return (this.studentNum == std.studentNum);
		}
		return false;
	}
	
	
}

public class EqualsTest {

	public static void main(String[] args) {
		
		Student Lee = new Student(100, "이순신");
		Student Lee2 = Lee;	//주소 같음
		Student Shin = new Student(100, "이순신");
		
		System.out.println(Lee == Shin);	//false (물리적 주소 다름)
		System.out.println(Lee.equals(Shin));
	}

}

--> Student Lee와 Shin의 물리적 주소는 다르나, 학번이 같으므로 논리적으로는 같은 학생이므로 equals()메서드를 재정의

	@Override
	public boolean equals(Object obj) {
		if( obj instanceof Student) {
			Student std = (Student)obj; //다운캐스팅
			return (this.studentNum == std.studentNum);
		}
		return false;
	}

--> upcasting된 obj가 Student 클래스의 객체인지 확인 후, Student 클래스로 다운캐스팅 한다

--> this의 학번과 비교대상으로 들어온 학생의 학번이 같은지 비교

 

 

* hashCode() 메서드

- hashCode : JVM에 인스턴스가 생성이 되었을 때 메모리 주소

- hashCode()메서드의 반환 값 : 인스턴스가 저장된 가상머신의 주소를 10진수로 반환

 

- 두 개의 서로 다른 메모리에 위치한 인스턴스가 동일하다는 것?

=> 논리적으로 동일 : equals()의 반환값이 true & 동일한 hashCode 값을 가짐 : hashCode()의 반환값이 동일