예전 포스팅에서 String.equals()에 대해서 알아보았다.
이번에는 Object.equals()에 대해서 알아보자.
String.equals() 포스팅
equals()는 두 객체를 비교하는 함수로써 모든 클래스의 조상인 Object 클래스의 함수이다. 그래서 @Override해서 쓴다.
- 두 개체가 모두
null을 가리키면 equals()는true를 반환한다.- 개체 중 하나가
null을 가리키면 equals()는false를 반환한다.- 두 개체가 모두 같으면 equals()는
true를 반환한다.- 그렇지 않으면, 등식 방법을 사용하여 등식을 결정한다.
Object 클래스의 equals() 함수는 객체의 주소를 비교한다.
즉, 같은 값을 가진 객체라 할지라도 따로 생성되었다면 false이다.
public static boolean equals(Object a, object b)
✔️ 매개변수
object a: 첫 번째 객체object b: 두 번째 객체
✔️ 리턴 값
- 메서드의 개체가 같으면
true를 반환하고, 그렇지 않으면 equals는false를 반환한다.
class Ball {
int num;
double weight;
public Ball(int num, double weight) {
this.num = num;
this.weight = weight;
}
}
class BallTest {
public static void main(String[] args) {
Ball b1 = new Ball(3, 150.5); // b4와 정보가 같지만, 주소값이 다르므로 다른 공
Ball b2 = new Ball(4, 150.5);
Ball b3 = new Ball(3, 160.8);
Ball b4 = new Ball(3, 150.5);
}
}
b1번공과 b4번의 정보는 같지만 주소값은 다르다. 따라서 다른 공으로 취급된다.
하지만, 우리는 Object.equals()를 통해서 객체를 정의할 때 같다 다르냐를 미리 정할 수 있다.
- 공의 번호와 무게가 같으면 같은 공으로 설정하자.
@Override
public boolean equals(Object other) {
return this == other;
}
Object.equals() 는 이런 느낌으로 앞으로 정의내리는 객체는 대부분 equals()가 있어야 한다.
비교를 하기 전에 먼저 고려할 점부터 세팅해야 한다.
- other가 null일 때
- other가 Ball객체가 아닐 때
파라미터 안에는 Object가 들어가있는데 모든 객체가 다 들어올 수 있다.
하지만 우리는 공이라는 객체만 비교해야 하기 때문에 다른 객체가 들어오면 안된다. null값도 마찬가지. 그래서 우리는 1번 2번같은 점을 미리 막아야한다
@Override
public boolean equals(Object other) {
// 무조건 false
// 1. other가 null일때
// 2. other가 Ball객체가 아닐때
if(other == null || !(other instanceof Ball)) {
return false;
}
Ball temp = (Ball)other;
return num == temp.num && weight == temp.weight;
}
최종적으로 이런식으로 Object.equals()를 활용하여 그 공이 같다 아니다를 미리 설정할 수 있다.
class Ball {
int num;
double weight;
public Ball(int num, double weight) {
this.num = num;
this.weight = weight;
}
// 공의 번호와 무게가 같으면 같은 공이다.
@Override
public boolean equals(Object other) {
if(other == null || !(other instanceof Ball)) {
return false;
}
Ball temp = (Ball)other;
return num == temp.num && weight == temp.weight;
}
}
class Ex1 {
public static void main(String[] args) {
Ball b1 = new Ball(3, 150.5);
Ball b2 = new Ball(4, 150.5);
Ball b3 = new Ball(3, 160.8);
Ball b4 = new Ball(3, 150.5);
System.out.println(b1.equals(b2));
System.out.println(b1.equals(b3));
System.out.println(b1.equals(b4));
}
}
[결과값]
false
false
true
class Human {
private String name;
private int age;
private String addr;
public Human(String name, int age, String addr) {
setName(name);
setAge(age);
setAddr(addr);
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAddr(String addr) {
this.addr = addr;
}
public String getAddr() {
return addr;
}
@Override
public boolean equals(Object other) {
if(other == null || !(other instanceof Human)) {
return false;
}
Human temp = (Human)other;
return name.equals(temp.getName()) && age == temp.getAge() && addr.equals(temp.getAddr());
}
}
class Ex3 {
public static void main(String[] args) {
Human h1 = new Human("영희", 25, "부산");
Human h2 = new Human("영희", 25, "부산");
Human h3 = new Human("철수", 20, "서울");
System.out.println(h1.equals(h2));
System.out.println(h1.equals(h3));
}
}
[결과값]
true
false
❗️ 조심해야할 점은 name과 addr은 String 타입인 참조형이기 때문에 name.equals(temp.getName()) addr.equals(temp.getAddr())
이렇게 String.equals()를 통해서 비교해야 한다.