大家好,欢迎来到IT知识分享网。
在Java中,对象是类的实例。对象则是类所定义的模板而创建出来的实体,它们封装了属性和方法。
Objects类可以用来简化对象的操作,完成常见的对象非空校验、对象比较、生成哈希码等任务从而提高代码的可读性。

一、判空
System.out.println(Objects.isNull(null)); 输出:true
二、对象为空设默认值
System.out.println(Objects.toString(null, "1")); 输出:1

三、对象比较是否相等
String str1 = "123"; String str2 = null; System.out.println(Objects.equals(str1, str2)); 输出: false
四、对象比较
//根据comparator的比较方法compareTo来对两对象进行比较 //返回值1代表前者大于后者,0表示相等,-1表示小于 Comparator<Integer> comparator = Integer::compareTo; int s = Objects.compare(2, 1, comparator); System.out.println(s); 输出:1

五、对象深度比较是否相等
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
六、为对象生成哈希码
String str = "1"; int hash1 = Objects.hashCode(str); //生成组合哈希 int hash2 = Objects.hash(str, 2); System.out.println(hash1); System.out.println(hash2); 输出: 49 2482

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/177347.html