하우스굿

java-Java null 확인 .equals () 대신 ==를 사용하는 이유

JAVA

질문

.equals () 대신 ==를 낸 것입니다. 그 이유는 무엇입니까?

 

 

해결

그래도 다른 두 가지입니다. ==(변수). .equals()계약서에 따라 같은지 확인합니다. "동일"할 수 있습니다. 그리고 equals는 메소드이므로 null참조에서 호출하려고하면 NullPointerException가된다는 사소한 세부 사항이 있습니다.

예를 들어 :

class Foo {
    private int data;

    Foo(int d) {
        this.data = d;
    }

    @Override
    public boolean equals(Object other) {
        if (other == null || other.getClass() != this.getClass()) {
           return false;
        }
        return ((Foo)other).data == this.data;
    }

    /* In a real class, you'd override `hashCode` here as well */
}

Foo f1 = new Foo(5);
Foo f2 = new Foo(5);
System.out.println(f1 == f2);
// outputs false, they're distinct object instances

System.out.println(f1.equals(f2));
// outputs true, they're "equal" according to their definition

Foo f3 = null;
System.out.println(f3 == null);
// outputs true, `f3` doesn't have any object reference assigned to it

System.out.println(f3.equals(null));
// Throws a NullPointerException, you can't dereference `f3`, it doesn't refer to anything

System.out.println(f1.equals(f3));
// Outputs false, since `f1` is a valid instance but `f3` is null,
// so one of the first checks inside the `Foo#equals` method will
// disallow the equality because it sees that `other` == null