개발/java

Objects.equals() 객체 비교

nix-be 2022. 9. 7. 22:56
728x90

1. Objects.equals() 란

  • 객체 비교 메소드

1-1. 번외

  • equals : 두 객체의 내용이 같은지, 동등성(equality) 를 비교하는 연산자
  • hashCode : 두 객체가 같은 객체인지, 동일성(identity) 를 비교하는 연산자

2. JDK의 Objects.equals() 소스 코드

package java.util;

public final class Objects {
  /**
   * Returns {@code true} if the arguments are equal to each other
   * and {@code false} otherwise.
   * Consequently, if both arguments are {@code null}, {@code true}
   * is returned and if exactly one argument is {@code null}, {@code
   * false} is returned.  Otherwise, equality is determined by using
   * the {@link Object#equals equals} method of the first
   * argument.
   *
   * @param a an object
   * @param b an object to be compared with {@code a} for equality
   * @return {@code true} if the arguments are equal to each other
   * and {@code false} otherwise
   * @see Object#equals(Object)
   */
  public static boolean equals(Object a, Object b) {
      return (a == b) || (a != null && a.equals(b));
  }

	public static int hash(Object... values) {
        return Arrays.hashCode(values);
  }

	public static boolean isNull(Object obj) {
        return obj == null;
  }

  /**
   * Returns {@code true} if the provided reference is non-{@code null}
   * otherwise returns {@code false}.
   *
   * @apiNote This method exists to be used as a
   * {@link java.util.function.Predicate}, {@code filter(Objects::nonNull)}
   *
   * @param obj a reference to be checked against {@code null}
   * @return {@code true} if the provided reference is non-{@code null}
   * otherwise {@code false}
   *
   * @see java.util.function.Predicate
   * @since 1.8
   */
  public static boolean nonNull(Object obj) {
      return obj != null;
  }
}

3. test 코드

String aa = null;
String bb = null;

System.out.println("Objects.equals(null, null): " + Objects.equals(aa, bb));

aa = "google";
bb = "google";
System.out.println("Objects.equals(google, google): " + Objects.equals(aa, bb));

aa= "android";
bb = "google";
System.out.println("Objects.equals(android, google): " + Objects.equals(aa, bb));

//결과
Objects.equals(null, null): true
Objects.equals(google, google): true
Objects.equals(android, google): false
  • 객체가 NULL 일때 true 나온다. 방지 하기 위해 아래 처럼 한다.
String aa = null;
String bb = "google";

if( aa != null && Objects.equals(aa,bb)){
		System.out.println("non null and equals");
} 
  • Objects.nonNull() 사용 예제
String aa = null;
String bb = "google";

if( Objects.nonNull(aa)  && Objects.equals(aa,bb)){
		System.out.println("non null and equals");
} 
  • isNull(), nonNull() 지원
public static boolean isNull(Object obj) {
        return obj == null;
 }

public static boolean nonNull(Object obj) {
    return obj != null;
}

728x90