20210115 java.util.Objects

java.util.Objects

基本信息

  • public final class Objects
  • rt.jar
  • 引入版本:1.7

公共方法

静态方法

静态方法
boolean equals(Object a, Object b)
可以避免空指针异常,null == null
boolean deepEquals(Object a, Object b)
equals 方法的不同是支持 多维数组 相等判断
int hashCode(Object o)
nullhashCode 为 0,其他返回对象的 hashCode() 方法返回值
int hash(Object... values)
生成 hashCode 的工具方法
String toString(Object o)
String toString(Object o, String nullDefault)
调用的是 String.valueOf() 方法,对象为 null 时,返回默认值
<T> int compare(T a, T b, Comparator<? super T> c)
执行比较器比较
<T> T requireNonNull(T obj)
<T> T requireNonNull(T obj, String message)
<T> T requireNonNull(T obj, Supplier<String> messageSupplier)
不为空时返回原对象,为空时引发空指针异常,异常信息可通过参数传入
boolean isNull(Object obj)
判断 obj == null
boolean nonNull(Object obj)
判断 obj != null

示例代码

@Test
public void test() {
    System.out.println(Objects.equals("a", "a"));   // true
    System.out.println(Objects.equals(null, null)); // true
    System.out.println(Objects.equals("a", null));  // false
    System.out.println(Objects.equals(null, "a"));  // false

    String[] arr1 = {"a", "b"};
    String[] arr2 = {"a", "b"};
    System.out.println(arr1.equals(arr2));  // false
    System.out.println(Objects.equals(arr1, arr2));  // false
    System.out.println(Objects.deepEquals(new String[]{"a", "b"}, new String[]{"a", "b"}));    // true
    System.out.println(Objects.deepEquals(new String[][]{{"a", "b"}, {"c", "d"}}, new String[][]{{"a", "b"}, {"c", "d"}}));    // true

    System.out.println(Objects.hashCode("abc"));    // 96354
    System.out.println(Objects.hash("a", "b", "c"));    // 126145

    System.out.println(Objects.toString(new String[][]{{"a", "b"}, {"c", "d"}}));   // [[Ljava.lang.String;@4f8e5cde
    System.out.println(Objects.toString(null, "xxx"));  // xxx

    System.out.println(Objects.compare("a", "B", String.CASE_INSENSITIVE_ORDER));   // -1

    System.out.println(Objects.isNull(null));   // true
    System.out.println(Objects.nonNull(null));  // false
    // System.out.println(Objects.requireNonNull((String) null));
    // System.out.println(Objects.requireNonNull((String) null, "error null"));
    // System.out.println(Objects.requireNonNull((String) null, () -> "error null Supplier"));
}
原文地址:https://www.cnblogs.com/huangwenjie/p/14280637.html