當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Java.util.Objects用法及代碼示例

Java 7 提出了一個新的 Objects 類,它有 9 個用於操作對象的靜態實用方法。這些實用程序包括用於計算對象的哈希碼、返回對象的字符串以及比較兩個對象的null-safe方法。

使用Objects類方法,可以巧妙地處理NullPointerException,還可以顯示定製的NullPointerException消息(如果發生異常)。

  1. 字符串 toString(對象 o):此方法返回對非空參數調用toString()方法和對空參數調用“null”方法的結果。
    Syntax : 
    public static String toString(Object o)
    Parameters : 
    o - an object
    返回:
    the result of calling toString() method for a non-null argument and 
    "null" for a null argument
    
  2. String toString(Object o, String nullDefault):該方法是上述方法的重載版本。如果第一個參數不為 null,則返回對第一個參數調用 toString() 方法的結果,否則返回第二個參數。
    Syntax : 
    public static String toString(Object o, String nullDefault)
    Parameters : 
    o - an object
    nullDefault - string to return if the first argument is null
    返回:
    the result of calling toString() method on the first argument if it is not null and
    the second argument otherwise.
    
    
    // Java program to demonstrate Objects.toString(Object o)  
    // and Objects.toString(Object o, String nullDefault) methods 
      
    import java.util.Objects; 
      
    class Pair<K, V>  
    { 
        public K key; 
        public V value; 
      
        public Pair(K key, V value)  
        { 
            this.key = key; 
            this.value = value; 
        } 
          
        @Override
        public String toString() { 
            return "Pair {key = " + Objects.toString(key) + ", value = " +  
                        Objects.toString(value, "no value") + "}"; 
              
            /* without Objects.toString(Object o) and  
             Objects.toString(Object o, String nullDefault) method 
             return "Pair {key = " + (key == null ? "null" : key.toString()) +  
         ", value = " + (value == null ? "no value" : value.toString()) + "}"; */
        } 
    } 
      
    class GFG 
    { 
        public static void main(String[] args)  
        { 
            Pair<String, String> p1 =  
                            new Pair<String, String>("GFG", "geeksforgeeks.org"); 
            Pair<String, String> p2 = new Pair<String, String>("Code", null); 
              
            System.out.println(p1); 
            System.out.println(p2); 
        } 
    } 

    輸出:

    Pair {key = GFG, value = geeksforgeeks.org}
    Pair {key = Code, value = no value}
    
  3. 布爾等於(對象a,對象b):如果參數彼此相等,則此方法為 true,否則為 false。因此,如果兩個參數都為 null,則返回 true,如果隻有一個參數為 null,則返回 false。否則,通過使用第一個參數的 equals() 方法來確定相等性。
    Syntax : 
    public static boolean equals(Object a,Object b)
    Parameters : 
    a - an object
    b - an object to be compared with a for equality
    返回:
    true if the arguments are equal to each other and false otherwise
    
    
    // Java program to demonstrate equals(Object a, Object b) method 
      
    import java.util.Objects; 
      
    class Pair<K, V>  
    { 
        public K key; 
        public V value; 
      
        public Pair(K key, V value)  
        { 
            this.key = key; 
            this.value = value; 
        } 
      
        @Override
        public boolean equals(Object o) 
        { 
            if (!(o instanceof Pair)) { 
                return false; 
            } 
            Pair<?, ?> p = (Pair<?, ?>) o; 
            return Objects.equals(p.key, key) && Objects.equals(p.value, value); 
              
        } 
    } 
      
    class GFG 
    { 
        public static void main(String[] args)  
        { 
            Pair<String, String> p1 =  
                    new Pair<String, String>("GFG", "geeksforgeeks.org"); 
              
            Pair<String, String> p2 =  
                    new Pair<String, String>("GFG", "geeksforgeeks.org"); 
              
            Pair<String, String> p3 =  
                    new Pair<String, String>("GFG", "www.geeksforgeeks.org"); 
              
            System.out.println(p1.equals(p2)); 
            System.out.println(p2.equals(p3)); 
              
        } 
    } 

    輸出:

    true
    false
    
  4. 布爾值 deepEquals(對象 a,對象 b):如果參數是,此方法返回 true彼此相等,否則為 false。兩個空值深度相等。如果兩個參數都是數組,則算法Arrays.deepEquals用於確定相等性。否則,通過使用第一個參數的 equals 方法來確定相等性。
    Syntax : 
    public static boolean deepEquals(Object a,Object b)
    Parameters : 
    a - an object
    b - an object to be compared with a for equality
    返回:
    true if the arguments are deeply equals to each other and false otherwise
    
  5. T requireNonNull(T obj):此方法檢查指定的對象引用是否不為空。該方法主要用於在方法和構造函數中進行參數驗證,如下例所示:
    Syntax : 
    public static  T requireNonNull(T obj)
    Type Parameters:
    T - the type of the reference
    Parameters : 
    obj - the object reference to check for nullity
    返回:
    obj if not null
    Throws:
    NullPointerException - if obj is null
    
  6. T requireNonNull(T obj,字符串消息):此方法是上述方法的重載版本,如果 obj 為 null,則具有自定義消息打印,如下例所示:
    Syntax : 
    public static  T requireNonNull(T obj,String message)
    Type Parameters:
    T - the type of the reference
    Parameters : 
    obj - the object reference to check for nullity
    message - detail message to be used in the event that a NullPointerException is thrown
    返回:
    obj if not null
    Throws:
    NullPointerException - if obj is null
    
    
    // Java program to demonstrate Objects.requireNonNull(Object o)  
    // and Objects.requireNonNull(Object o, String message) methods 
      
    import java.util.Objects; 
      
    class Pair<K, V>  
    { 
        public K key; 
        public V value; 
      
        public Pair(K key, V value)  
        { 
            this.key = key; 
            this.value = value; 
        } 
      
        public void setKey(K key) { 
            this.key = Objects.requireNonNull(key); 
        } 
          
        public void setValue(V value) { 
            this.value = Objects.requireNonNull(value, "no value"); 
        } 
    } 
      
    class GFG 
    { 
        public static void main(String[] args)  
        { 
            Pair<String, String> p1 =  
                        new Pair<String, String>("GFG", "geeksforgeeks.org"); 
              
            p1.setKey("Geeks"); 
              
            // below statement will throw NPE with customized message 
            p1.setValue(null); 
              
        } 
    } 

    輸出:

    Exception in thread "main" java.lang.NullPointerException: no value
        at java.util.Objects.requireNonNull(Objects.java:228)
        at Pair.setValue(GFG.java:22)
        at GFG.main(GFG.java:36)
    
  7. int hashCode(對象 o):此方法返回非空參數的哈希碼,對於空參數返回 0。
    Syntax : 
    public static int hashCode(Object o)
    Parameters : 
    o - an object
    返回:
    the hash code of a non-null argument and 0 for a null argument
    
    
    // Java program to demonstrate Objects.hashCode(Object o) object 
      
    import java.util.Objects; 
      
    class Pair<K, V>  
    { 
        public K key; 
        public V value; 
      
        public Pair(K key, V value)  
        { 
            this.key = key; 
            this.value = value; 
        } 
      
        @Override
        public int hashCode() 
        { 
            return (Objects.hashCode(key) ^ Objects.hashCode(value)); 
              
            /* without Objects.hashCode(Object o) method 
            return (key == null ? 0 : key.hashCode()) ^  
            (value == null ? 0 : value.hashCode()); */
        } 
    } 
      
    class GFG 
    { 
        public static void main(String[] args)  
        { 
            Pair<String, String> p1 =  
                    new Pair<String, String>("GFG", "geeksforgeeks.org"); 
            Pair<String, String> p2 =  
                    new Pair<String, String>("Code", null); 
            Pair<String, String> p3 = new Pair<String, String>(null, null); 
              
            System.out.println(p1.hashCode()); 
            System.out.println(p2.hashCode()); 
            System.out.println(p3.hashCode()); 
        } 
    } 

    輸出:

    450903651
    2105869
    0
    
  8. int hash(對象…值):此方法為輸入值序列生成哈希碼。生成哈希碼的方式就好像所有輸入值都放入一個數組中,並且該數組通過調用 Arrays.hashCode(Object[]) 進行哈希處理。
    此方法對於在包含多個字段的對象上實現 Object.hashCode() 非常有用。例如,如果一個對象具有 x、y 和 z 三個字段,則可以編寫:
    @Override 
    public int hashCode() {
         return Objects.hash(x, y, z);
    }
    

    注意:當提供單個對象引用時,返回值不等於該對象引用的哈希碼。該值可以通過調用 hashCode(Object) 來計算。

    Syntax : 
    public static int hash(Object... values)
    Parameters : 
    values - the values to be hashed
    返回:
    a hash value of the sequence of input values
    
    
    // Java program to demonstrate Objects.hashCode(Object o) object 
      
    import java.util.Objects; 
      
    class Pair<K, V>  
    { 
        public K key; 
        public V value; 
      
        public Pair(K key, V value)  
        { 
            this.key = key; 
            this.value = value; 
        } 
      
        @Override
        public int hashCode() 
        { 
            return (Objects.hash(key,value)); 
        } 
    } 
      
    class GFG 
    { 
        public static void main(String[] args)  
        { 
            Pair<String, String> p1 =  
                    new Pair<String, String>("GFG", "geeksforgeeks.org"); 
            Pair<String, String> p2 =  
                    new Pair<String, String>("Code", null); 
            Pair<String, String> p3 = new Pair<String, String>(null, null); 
              
            System.out.println(p1.hashCode()); 
            System.out.println(p2.hashCode()); 
            System.out.println(p3.hashCode()); 
        } 
    } 

    輸出:

    453150372
    65282900
    961
    
  9. int 比較(T a,T b,比較器 c):像往常一樣,如果參數相同,則此方法返回 0,否則返回 c.compare(a, b)。因此,如果兩個參數都為 null,則返回 0。

    請注意,如果參數之一為 null,則可能會或可能不會拋出 NullPointerException,具體取決於比較器選擇對 null 值采用的排序策略(如果有)。

    Syntax : 
    public static  int compare(T a,T b,Comparator c)
    Type Parameters:
    T - the type of the objects being compared
    Parameters : 
    a - an object
    b - an object to be compared with a
    c - the Comparator to compare the first two arguments
    返回:
    0 if the arguments are identical and c.compare(a, b) otherwise.
    

注意:在 Java 8 中,Objects 類多了 3 個方法。他們兩個人(isNull(對象 o)非空(對象 o)) 用於檢查空值參考。第三個是 requireNonNull 方法的又一個重載版本。參考這裏.



相關用法


注:本文由純淨天空篩選整理自gaurav miglani大神的英文原創作品 Java.util.Objects class in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。