programing

Java null을 통해 .timeout() 대신 ==을 사용하는 이유를 확인합니다.

yoursource 2022. 9. 17. 22:05
반응형

Java null을 통해 .timeout() 대신 ==을 사용하는 이유를 확인합니다.

Java에서는 null check를 할 때 .xx가 아닌 ==를 사용해야 한다고 합니다.그 이유는 무엇입니까?

그 둘은 완전히 다른 것이다. ==는 변수에 포함된 오브젝트 참조(있는 경우)를 비교합니다. .equals()는 평등의 의미에 대한 계약에 따라 두 객체가 동일한지 여부를 확인합니다.계약에 따라 서로 다른 두 객체 인스턴스가 "동일" 수 있습니다.그리고 그 이후로 세세한 부분까지equals메서드는 a 하려고 할 때 사용합니다.nullNullPointerException.

예:

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

를 호출했을 .equals()null 얻을 수 있다NullPointerException

따라서 적용되는 메서드를 호출하기 전에 항상 무효를 체크하는 것이 좋습니다.

if(str!=null && str.equals("hi")){
 //str contains hi
}  

기타 항목

승인된 답변 외에 (https://stackoverflow.com/a/4501084/6276704):

Java 1.7 이후 null일 수 있는 두 개체를 비교하려면 다음 기능을 권장합니다.

Objects.equals(onePossibleNull, twoPossibleNull)

java.displaces를 클릭합니다.물건들

이 클래스는 객체에서 동작하기 위한 정적 유틸리티 메서드로 구성됩니다.이러한 유틸리티에는 개체의 해시 코드를 계산하고, 개체의 문자열을 반환하고, 두 개체를 비교하는 null-safe 또는 null-torrant 메서드가 포함됩니다.

이후: 1.7

Java 0 또는 null은 단순한 유형이며 개체가 아닙니다.

메서드 equals()는 단순한 유형에는 구축되지 않았습니다.==와 간단한 유형을 매칭할 수 있습니다.

Object.equals는 null 안전합니다.단, 2개의 객체가 null일 경우 object.equals는 true가 반환되므로 비교할 객체가 null이 아닌지(또는 null 값을 유지하는지) 확인한 후 비교에 object.equals를 사용하십시오.

String firstname = null;
String lastname = null;

if(Objects.equals(firstname, lastname)){
    System.out.println("equal!");
} else {
    System.out.println("not equal!");
}

위의 예제 스니펫은 동일하게 반환됩니다!

foo.equals(null)

foo가 null이면 어떻게 됩니까?

Null Pointer가 표시됩니다.예외.

오브젝트 변수가 늘인 경우 해당 변수에 대해 equals() 메서드를 호출할 수 없으므로 null 오브젝트 참조 체크가 적절합니다.

null 객체 참조에서 equals를 호출하려고 하면 null 포인터 예외가 느려집니다.

소식통에 따르면 기본 방식 구현에 무엇을 사용할지는 중요하지 않습니다.

public boolean equals(Object object) {
    return this == object;
}

확실한 은 아닙니다equals커스텀 클래스입니다.

= > .disply 메서드를 사용하는 경우

if(obj.equals(null))  

// Which mean null.equals(null) when obj will be null.

obj가 무효가 되면 Null Point Exception이 느려집니다.

==를 사용해야 합니다.

if(obj == null)

참조를 비교합니다.

예를 들면 다음과 같습니다.str != null그렇지만str.equals(null)사용할 때org.json

 JSONObject jsonObj = new JSONObject("{field :null}");
 Object field = jsonObj.get("field");
 System.out.println(field != null);        // => true
 System.out.println( field.equals(null)); //=> true
 System.out.println( field.getClass());  // => org.json.JSONObject$Null




편집: org.json 입니다.JSONObject$Null 클래스:

/**
 * JSONObject.NULL is equivalent to the value that JavaScript calls null,
 * whilst Java's null is equivalent to the value that JavaScript calls
 * undefined.
 */
private static final class Null {

    /**
     * A Null object is equal to the null value and to itself.
     *
     * @param object
     *            An object to test for nullness.
     * @return true if the object parameter is the JSONObject.NULL object or
     *         null.
     */
    @Override
    public boolean equals(Object object) {
        return object == null || object == this;
    }  
}

equal은 Object 클래스에서 파생된 함수이므로 이 함수는 클래스의 항목을 비교합니다.null과 함께 사용하면 클래스 내용이 null이 아닌 false cause class content가 반환됩니다.또한 ==는 개체에 대한 참조를 비교합니다.

따라서 이 솔루션에서는 혼란을 겪지 않고 문제를 회피할 수 있습니다.

if(str.trim().length() <=0 ) {
   // is null !
}

나는 어젯밤에 이 사건을 접했다.
저는 간단히 다음과 같이 판단합니다.

null에 대한 equals() 메서드없습니다.
따라서 존재하지 않는 메서드를 호출할 수 없습니다.
-->> 그렇기 때문에 ==를 사용하여 늘을 확인합니다.

네 코드는 디메터의 법칙을 어긴다그렇기 때문에 디자인 자체를 리팩터링하는 것이 좋습니다.회피책으로 옵션 기능을 사용할 수 있습니다.

   obj = Optional.ofNullable(object1)
    .map(o -> o.getIdObject11())
    .map(o -> o.getIdObject111())
    .map(o -> o.getDescription())
    .orElse("")

위는 오브젝트의 계층을 체크하는 것입니다.단순히 사용하다

Optional.ofNullable(object1) 

체크할 오브젝트가1개밖에 없는 경우

도움이 되었으면 좋겠다!!!

넌 언제나 할 수 있어

if (str == null || str.equals(null))

그러면 먼저 개체 참조를 확인한 후 참조가 null이 아닌 경우 개체 자체를 확인합니다.

언급URL : https://stackoverflow.com/questions/4501061/java-null-check-why-use-instead-of-equals

반응형