Java 常用工具类(Objects / Arrays / Collections 等)
Java 提供了丰富的工具类来简化常见操作。理解这些工具类的使用可以提高开发效率。本章将详细介绍 Java 中的常用工具类。
java.util.Objects 方法(requireNonNull、equals、hashCode)
Objects 类概述
Objects 类(Java 7+)提供了操作对象的静态方法,主要用于空值检查和对象比较。
requireNonNull
检查对象是否为 null,为 null 时抛出异常:
import java.util.Objects;
public void method(String str) {
// 检查 null,如果为 null 抛出 NullPointerException
String nonNull = Objects.requireNonNull(str);
// 带自定义消息
String nonNull2 = Objects.requireNonNull(str, "字符串不能为 null");
// 带消息提供者(延迟计算)
String nonNull3 = Objects.requireNonNull(str, () -> "字符串不能为 null");
}
equals
安全的对象比较,避免空指针异常:
String str1 = "hello";
String str2 = "hello";
String str3 = null;
// ✅ 安全比较
boolean equal1 = Objects.equals(str1, str2); // true
boolean equal2 = Objects.equals(str1, str3); // false(不会抛异常)
boolean equal3 = Objects.equals(str3, str3); // true(两个 null 相等)
// ❌ 不安全比较
// boolean equal = str1.equals(str3); // 可能抛出 NullPointerException
hashCode
计算对象的哈希码,null 安全:
String str = "hello";
int hash = Objects.hashCode(str); // 如果 str 为 null,返回 0
// 多个对象的哈希码
int combinedHash = Objects.hash("hello", 123, true);
其他常用方法
// 检查是否为 null
boolean isNull = Objects.isNull(str); // str == null
boolean nonNull = Objects.nonNull(str); // str != null
// 深度比较
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
boolean deepEqual = Objects.deepEquals(arr1, arr2); // true
// toString(null 安全)
String result = Objects.toString(str); // 如果 null 返回 "null"
String result2 = Objects.toString(str, "默认值"); // 如果 null 返回 "默认值"