문제
아래 2개의 클래스 파일을 작성하고, 메인에서 아래와 같은 실행결과가 나오도록 코딩하시오.
Student클래스
멤버변수
private int studentNum
private String name
멤버함수
public int hashCode()
public boolean equals (Object obj)
*Object의 hashCode()와 equals()를 재정의하여 출력결과와 같이 나오도록 구현해보세요.
getter()구현
HashSetExample1(실행클래스)
결과
총 객체수 : 6
학번: 4 , 이름: 황희정
학번: 1 , 이름: 손연재
학번: 3 , 이름: 신동욱
학번: 1 , 이름: 신은혁
학번: 2 , 이름: 김연아
학번: 5 , 이름: 김동우
코드
class Student7 {
private int studentNum;
private String name;
public Student7(int studentNum, String name) {
this.studentNum = studentNum;
this.name = name;
}
public int getStudentNum() {
return studentNum;
}
public String getName() {
return name;
}
public int hashCode() {
// System.out.println("hash");
return Objects.hash(studentNum, name);
}
public boolean equals(Object obj) {
// Student7 s = (Student7) obj;
// System.out.println("equal");
if (this.studentNum == ((Student7) obj).studentNum) {
if (this.name.equals(((Student7) obj).name)) {
return true;
} else
return false;
}
return false;
}
}
public class HashSetExample1 {
public static void main(String[] args) {
HashSet<Student7> set = new HashSet<>();
set.add(new Student7(1, "신은혁"));
set.add(new Student7(2, "김연아"));
set.add(new Student7(1, "손연재"));
set.add(new Student7(2, "김연아"));
set.add(new Student7(5, "김동우"));
set.add(new Student7(4, "황희정"));
set.add(new Student7(1, "신은혁"));
set.add(new Student7(3, "신동욱"));
System.out.println("총 객체수 : " + set.size());
Iterator<Student7> it = set.iterator();
while (it.hasNext()) {
Student7 stu = it.next();
System.out.println("학번: " + stu.getStudentNum() + " , " + "이름: " + stu.getName());
}
}
}
equals와 hashCode는 왜 같이 정의하여야 할까?
hashCode 메서드의 리턴 값이 우선 일치하고 equals 메서드의 리턴 값이 true여야 논리적으로 같은 객체라고 판단한다.

참고
https://tecoble.techcourse.co.kr/post/2020-07-29-equals-and-hashCode/
equals와 hashCode는 왜 같이 재정의해야 할까?
equals와 hashCode는 같이 재정의하라는 말을 다들 한 번쯤 들어봤을 것이다. 대부분의 IDE Generate 기능에서도 equals와 hashCode를 같이 재정의해주며 lombok에서도 EqualsAndHashCode…
tecoble.techcourse.co.kr
'Java' 카테고리의 다른 글
| [Java] Map 사용 예제 (23-1) (0) | 2023.09.14 |
|---|---|
| [Java] ArrayList 사용 예제 (22-2) (0) | 2023.09.13 |
| [Java] 자바 컬렉션 HashSet (21-4) (0) | 2023.09.07 |
| [Java] 자바 컬렉션 ArrayList (21-3) (1) | 2023.09.07 |
| [Java] 자바 컬렉션 ArrayList (21-2) (0) | 2023.09.07 |