1. Objects API概述
- Objects类是一个工具类,包含一系列的静态工具方法;
- 有如下用途: (1) requireNotNull函数要求一个对象不为空,为空则抛异常;
(2) isNUll和notNULL函数检查一个对象是否为空;
(3) equals检查两个对象是否相同;
(4) deepEquals检查两个数据是否完全相同;
(5) hashCode 返回hash码,hash产生hash码;
(6) toString 对象toString
2. Objects UML
3. Object源码分析
package java.util;
import java.util.function.Supplier;
public final class Objects {
private Objects() {
throw new AssertionError("No java.util.Objects instances for you!");
}
//比较a b 两个对象是否相等
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
//比较两个数组各个元素是否相等
public static boolean deepEquals(Object a, Object b) {
if (a == b)
return true;
else if (a == null || b == null)
return false;
else
return Arrays.deepEquals0(a, b);
}
//返回对象o的hashCode
public static int hashCode(Object o) {
return o != null ? o.hashCode() : 0;
}
//产生values的hashCode
public static int hash(Object... values) {
return Arrays.hashCode(values);
}
//返回对象o的toString
public static String toString(Object o) {
return String.valueOf(o);
}
//如果对象不为null,则toString,为空,返回设置的默认nullDefault字符串
public static String toString(Object o, String nullDefault) {
return (o != null) ? o.toString() : nullDefault;
}
// 根据规则c来比较a b
public static <T> int compare(T a, T b, Comparator<? super T> c) {
return (a == b) ? 0 : c.compare(a, b);
}
//为null返回true
public static boolean isNull(Object obj) {
return obj == null;
}
//不为null 返回true
public static boolean nonNull(Object obj) {
return obj != null;
}
/**
*requireNonNull要求obj对象不为null,否则抛NullPointerException
*
*/
public static <T> T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}
public static <T> T requireNonNull(T obj, String message) {
if (obj == null)
throw new NullPointerException(message);
return obj;
}
public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier) {
if (obj == null)
throw new NullPointerException(messageSupplier.get());
return obj;
}
}
3. Objects示例