본문 바로가기
  • Adillete
【Java】

java8에서 Object.equals 재정의해서 사용하기

by 아딜렛 2025. 8. 4.

 

 

 

public class Student {
    private int no1;
    private String name1;

    public Student(int no1, String name1) {
        this.no1 = no1;
        this.name1 = name1;
    }

    public int getNo() {
        return no1;
    }

    public String getName() {
        return name1;
    }

    @Override
    public boolean equals(Object obj) {
        //1. 동일 참조 체크
        if(this==obj) return true;
        //2. null 체크 및 타입 체크
        if (obj == null ||  !(obj instanceof Student)) return false;
        //타입 캐스팅
        Student student = (Student) obj;
        //필드 비교 (학생 번호와 이름)
        return getNo() == student.getNo() && Objects.equals(getName(), student.getName());
    }