2 min read

<Java> 객체 비교시, “==”과 “equals”의 차이

1. “==” 연산자

  • == 연산자의 경우 객체의 주솟값을 비교하는 역할을 하기에, 비교하려는 객체가 동일한 객체인지를 판별한다.
  • 디테일하게 들어가면, Primitive Type의 객체에 대해서는 값 비교가 가능하고, Reference Type에 대해서는 주소 비교를 수행한다.
  • 이를 더 엄밀하게 서술하면 Primitive Type의 객체는 Constant Pool의 특정한 값을 참조하는 변수이기에, 결국 Constant Pool내의 동일한 주소를 비교한다.(해당 주소가 동일하기에 ==을 사용해서 비교가 가능)

2. “equals” 메서드

  • 원래 equals()의 경우 Object 클래스의 메서드이고 이는 == 연산자와 동일하게 주소값을 비교를 수행하는 메서드이다. 흔히 우리가 문자열 비교를 위해 사용하는 equals()의 경우 String 클래스에서 오버라이딩을 함으로써 문자열 간의 비교가 가능해졌다.
  • 아래의 코드의 경우 오버라이딩을 진행하지않은 Object클래스의 메서드이다.
public class EqualsEx{
    public static void main(String[] args){
        Value v1 = new Value(10);
        Value v2 = new Value(10);
        
        if(v1.equals(v2)){
            System.out.println("true");
        }
        else{
            System.out.println("false");//false 출력
        }
        
        v2 = v1;//v1 인스턴스주소가 v2에 저장된다.
        if(v1.equals(v2)){
            System.out.println("true");//true 출력
        }
        else{
            System.out.println("false");
        }
    }
}

class Value{
    int value;
    
    Value(int Value){
        this.value = value;
    }
}

  • 아래의 코드는 Person이라는 클래스에서 equals메서드를 오버라이딩하여 실제 데이터를 비교하도록 했다.
class Person{
    long id;
    
    public boolean equals(Object obj){
        if(obj instanceof Person){
            return id == ((Person)obj).id;
        }
        else{
            return false;
        }
    }
    Person(long id){
        this.id = id;
    }
}

public class EqualsEx{
    public static void main(String[] args){
        Person p1 = new Person(21710736L);
        Person p2 = new Person(21710736L);
        
        if(p1 == p2){
            System.out.println("true");
        }
        else{
            System.out.println("fasle");
        }
        if(p1.equals(p2)){
            System.out.println("true");
        }
        else{
            System.out.println("fasle");
        }
    }
}
  • 아래의 코드는 실제 String 클래스가 오버라이딩한 equals() 코드이다.
public boolean equals(Object anObject) {  
      if (this == anObject) {  
          return true;  
      }  
      if (anObject instanceof String) {  
          String anotherString = (String) anObject;  
          int n = value.length;  
          if (n == anotherString.value.length) {  
              char v1[] = value;  
              char v2[] = anotherString.value;  
              int i = 0;  
              while (n-- != 0) {  
                  if (v1[i] != v2[i])  
                          return false;  
                  i++;  
              }  
              return true;  
          }  
      }  
      return false;  
  }