<返回更多

Java - Objects工具类

2020-07-24    
加入收藏

Objects类是JAVA.util包下的一个工具类,它只拥有私有的构造函数,因此无法对其进行实例化,但它提供了一系列针对object对象的静态方法,包括equal,hash, 参数检查等。

Java - Objects工具类

Objects类的所有静态方法

下面对这个工具类的静态方法做具体的介绍:

判断2个object对象是否相等。

/* Since 1.7 */ 
public static boolean equals(Object a, Object b) {
        return (a == b) || (a != null && a.equals(b));
}

例子:

    private static void testEquals() {
        System.out.println("null equals null:" + Objects.equals(null,null));
        System.out.println("1 equals null:" + Objects.equals(1,null));
        System.out.println("null equals 1:" + Objects.equals(null,1));
        System.out.println("ABC equals ABC:" + Objects.equals("ABC","ABC"));
        System.out.println("1 equals ABC:" + Objects.equals(1,"ABC"));
    }

输出结果:

null equals null:true
1 equals null:false
null equals 1:false
ABC equals ABC:true
1 equals ABC:false

判断2个对象是否相等,如果是对象是数组,将会对数组的元素进行比较。

  /* Since 1.7 */   
  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);
    }

例子:

    private static void testDeepEquals() {
        System.out.println("null equals null:" + Objects.deepEquals(null,null));
        System.out.println("1 equals null:" + Objects.deepEquals(1,null));
        System.out.println("null equals 1:" + Objects.deepEquals(null,1));
        System.out.println("ABC equals ABC:" + Objects.deepEquals("ABC","ABC"));
        System.out.println("1 equals ABC:" + Objects.deepEquals(1,"ABC"));
        System.out.println("string array equals string array:" + Objects.deepEquals(new String[]{"1","2"},new String[]{"1","2"}));
        System.out.println("int array equals string array:" + Objects.deepEquals(new Integer[]{1,2},new String[]{"1","2"}));
    }

输出结果:

null equals null:true
1 equals null:false
null equals 1:false
ABC equals ABC:true
1 equals ABC:false
string array equals string array:true
int array equals string array:false

获取对象的hash码,如果object为null,返回0。

/* Since 1.7 */ 
public static int hashCode(Object o) {
     return o != null ? o.hashCode() : 0;
}

例子:

    private static void testHashCode() {
        System.out.println("hash for int:" + Objects.hashCode(1));
        System.out.println("hash for string:" + Objects.hashCode("1"));
        System.out.println("hash for long:" + Objects.hashCode(1L));
        System.out.println("hash for double:" + Objects.hashCode(1D));
        System.out.println("hash for null:" + Objects.hashCode(null));
    }

输出:

hash for int:1
hash for string:49
hash for long:1
hash for double:1072693248
hash for null:0

计算数组的hash值(since 1.7)。

   /* Since 1.7 */  
   public static int hash(Object... values) {
        return Arrays.hashCode(values);
    }

例子:

    private static void testHash() {
        System.out.println("int array hash:" + Objects.hash(1,2,4));
        System.out.println("string array hash:" + Objects.hash("1","2","4"));
        System.out.println("mixed array hash:" + Objects.hash("1",2,"4"));
    }

输出:

int array hash:30818
string array hash:78482
mixed array hash:76994

把object对象转换成字符串。

   /* Since 1.7 */  
   public static String toString(Object o) {
        return String.valueOf(o);
    }
   /* Since 1.7 */ 
    public static String toString(Object o, String nullDefault) {
        return (o != null) ? o.toString() : nullDefault;
    }

例子:

    private static void testToString() {
        System.out.println("int str:" + Objects.toString(1));
        System.out.println("double str:" + Objects.toString(1.01D));
        System.out.println("null:" + Objects.toString(null, "1000"));
    }

输出结果:

int str:1
double str:1.01
null:1000

使用指定的Comparator来对2个值进行比较。

   /* Since 1.7 */ 
   public static <T> int compare(T a, T b, Comparator<? super T> c) {
        return (a == b) ? 0 :  c.compare(a, b);
    }

例子:

    private static void testCompare() {
        System.out.println("int compare 1:" + Objects.compare(1,2, Comparator.naturalOrder()));
        System.out.println("int compare 2:" + Objects.compare(1,2, Comparator.reverseorder()));
    }

输出结果:

int compare 1:-1
int compare 2:1

如果object为null,将会抛出NullPointerException,否则返回它自身。

   /**
  * Since 1.7
  */ 
  public static <T> T requireNonNull(T obj) {
        if (obj == null)
            throw new NullPointerException();
        return obj;
    }
	
  /**
  * Since 1.7
  */
    public static <T> T requireNonNull(T obj, String message) {
        if (obj == null)
            throw new NullPointerException(message);
        return obj;
    }
   
  /**
  * Since 1.8
  */
   public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier) {
        if (obj == null)
            throw new NullPointerException(messageSupplier == null ?
                                           null : messageSupplier.get());
        return obj;
    }

例子:

    private static void testRequireNotNull() {
        System.out.println("not null:" + Objects.requireNonNull("ABC"));
        try {
            System.out.println("null:" + Objects.requireNonNull(null, "input is required1"));
        }catch(NullPointerException e){
            System.out.println("exception:" + e.getMessage());
        }

        try {
            System.out.println("null:" + Objects.requireNonNull(null, ()->"input is required2"));
        }catch(NullPointerException e){
            System.out.println("exception:" + e.getMessage());
        }
    }

输出结果:

not null:ABC
exception:input is required1
exception:input is required2

如果object为null,返回默认值。

     /* since 9 */  
   public static <T> T requireNonNullElse(T obj, T defaultObj) {
        return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj");
    }
    /* since 9 */  
    public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier) {
        return (obj != null) ? obj
                : requireNonNull(requireNonNull(supplier, "supplier").get(), "supplier.get()");
    }

例子:

    private static void testRequireNotNullElse() {
        System.out.println("null else:" + Objects.requireNonNullElse(null,"CEFG"));
        System.out.println("null else get:" + Objects.requireNonNullElseGet(null,()->"HYZ"));
    }

输出结果:

null else:CEFG
null else get:HYZ

判断是否为null。

     /* since 1.8 */ 
    public static boolean isNull(Object obj) {
        return obj == null;
    }

     /* since 1.8 */ 
   public static boolean nonNull(Object obj) {
        return obj != null;
    }

例子:

    private static void testNullAndNotNull() {
        System.out.println("null 1:" + Objects.isNull(null));
        System.out.println("null 2:" + Objects.nonNull(null));
        System.out.println("not null 1:" + Objects.isNull("ABC"));
        System.out.println("not null 2:" + Objects.nonNull("ABC"));
    }

输出结果:

null 1:true
null 2:false
not null 1:false
not null 2:true

检查index是否在[0,length),如果是,返回index,否则抛出IndexOutOfBoundsException。

   /* since 9 */ 
   public static int checkIndex(int index, int length) {
        return Preconditions.checkIndex(index, length, null);
    }

例子:

    private static void testCheckIndex() {
        System.out.println("index in:" + Objects.checkIndex(5, 100));
        try{
            System.out.println("index in:" + Objects.checkIndex(100, 100));
        }catch (IndexOutOfBoundsException e){
            System.out.println("exception:" + e.getMessage());
        }
    }

输出结果:

index in:5
exception:Index 100 out of bounds for length 100

检查[fromIndex,toIndex) 是否在[0, length)范围内,如果是,返回fromIndex,否则抛出IndexOutOfBoundsException异常。

   /* Since 9 */ 
   public static int checkFromToIndex(int fromIndex, int toIndex, int length) {
        return Preconditions.checkFromToIndex(fromIndex, toIndex, length, null);
    }

例子:

    private static void testCheckFromToIndex() {
        System.out.println("index in:" + Objects.checkFromToIndex(5, 10, 100));
        try{
            System.out.println("index out:" + Objects.checkFromToIndex(5,101, 100));
        }catch (IndexOutOfBoundsException e){
            System.out.println("exception:" + e.getMessage());
        }
    }

输出结果:

index in:5
exception:Range [5, 101) out of bounds for length 100

检查[fromIndex,fromIndex+size) 是否在[0, length)范围内,如果是,返回fromIndex,否则抛出IndexOutOfBoundsException异常。

   /* Since 9 */
   public static int c(int fromIndex, int size, int length) {
        return Preconditions.checkFromIndexSize(fromIndex, size, length, null);
    }

例子:

    private static void testCheckFromIndexSize() {
        System.out.println("index in:" + Objects.checkFromIndexSize(5, 10, 100));
        try{
            System.out.println("index out:" + Objects.checkFromIndexSize(5,101, 100));
        }catch (IndexOutOfBoundsException e){
            System.out.println("exception:" + e.getMessage());
        }
    }

输出结果:

index in:5
exception:Range [5, 5 + 101) out of bounds for length 100
声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>