专业的JAVA编程教程与资源

网站首页 > java教程 正文

100个Java工具类之78:对象处理工具类Objects

temp10 2025-03-04 13:56:23 java教程 7 ℃ 0 评论

在Java中,对象是类的实例。对象则是类所定义的模板而创建出来的实体,它们封装了属性和方法。

Objects类可以用来简化对象的操作,完成常见的对象非空校验、对象比较、生成哈希码等任务从而提高代码的可读性。

100个Java工具类之78:对象处理工具类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 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


Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表