100个Java工具类之78:对象处理工具类Objects
在Java中,对象是类的实例。对象则是类所定义的模板而创建出来的实体,它们封装了属性和方法。
Objects类可以用来简化对象的操作,完成常见的对象非空校验、对象比较、生成哈希码等任务从而提高代码的可读性。
一、判空
Bash
System.out.println(Objects.isNull(null));
输出:true
二、对象为空设默认值
Bash
System.out.println(Objects.toString(null, "1"));
输出:1
三、对象比较是否相等
Bash
String str1 = "123";
String str2 = null;
System.out.println(Objects.equals(str1, str2));
输出: false
四、对象比较
Bash
//根据comparator的比较方法compareTo来对两对象进行比较
//返回值1代表前者大于后者,0表示相等,-1表示小于
Comparator comparator = Integer::compareTo;
int s = Objects.compare(2, 1, comparator);
System.out.println(s);
输出:1
五、对象深度比较是否相等
Bash
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
int[] arr3 = {1, 2, 4};
System.out.println(Objects.deepEquals(arr1, arr2));
System.out.println(Objects.deepEquals(arr1, arr3));
输出: true false
六、为对象生成哈希码
Bash
String str = "1";
int hash1 = Objects.hashCode(str);
//生成组合哈希
int hash2 = Objects.hash(str, 2);
System.out.println(hash1);
System.out.println(hash2);
输出:
49
2482