D02.深入 Java SE/API‎ > ‎Java 7‎ > ‎

java.util.Objects

Java SE 7, Objects class, http://download.java.net/jdk7/docs/api/java/util/Objects.html

Objects 類別提供全為 Static 方法,
  • null-safe
  • null-tolerant



java.util
Class Objects

java.lang.Object
extended by java.util.Objects

public final class Objects
extends Object

This class consists of static utility methods for operating on objects. These utilities include null-safe or null-tolerant methods for computing the hash code of an object, returning a string for an object, and comparing two objects.

Since:
1.7

方法概要
修飾子與型別 方法描述與描述
static
<T> int
compare(T a, T b, Comparator<? super T> c)
          Returns 0 if the arguments are identical and c.compare(a, b) otherwise.
static boolean deepEquals(Object a, Object b)
          Returns true if the arguments are deeply equal to each other and false otherwise.
static boolean equals(Object a, Object b)
          Returns true if the arguments are equal to each other and false otherwise.
static int hash(Object... values)
          Generates a hash code for a sequence of input values.
static int hashCode(Object o)
          Returns the hash code of a non-null argument and 0 for a null argument.
static
<T> T
nonNull(T obj)
          Checks that the specified object reference is not null.
static
<T> T
nonNull(T obj, String message)
          Checks that the specified object reference is not null and throws a customized NullPointerException if it is.
static String toString(Object o)
          Returns the result of calling toString for a non-null argument and "null" for a null argument.
static String toString(Object o, String nullDefault)
          Returns the result of calling toString on the first argument if the first argument is not null and returns the second argument otherwise.


一個空安全(null-safe)的equals(arg1, arg2)方法,如果兩個參數都為null返回true,如果只有一個為 null 返回 false,其他情況則調用arg1.equals(arg2)

一套針對所有原生類型(int、long等)的compareTo(arg1, arg2)方法

toString(arg),通過反射將對象中的所有屬性都寫到返回的輸出字符串中
對clone()方法的一個輔助實現

一個空安全的hashCode()實現,對於值為null的對象該方法返回0。


References


  1. http://www.baptiste-wicht.com/2010/04/java-7-the-new-java-util-objects-class/
  2. http://63.246.7.136/cn/news/2009/09/jdk7-java-utils-object
Comments