当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。