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


Java OptionalLong equals()用法及代码示例


OptionalLong帮助我们创建一个可能包含或可能不包含Long值的对象。 equals(Object obj)方法可帮助我们将此OptionalLong对象与传递的对象作为参数进行比较,如果对象相等,则返回true。

如果满足以下条件,则认为另一个对象与此OptionalLong相等:

  • 它也是一个OptionalLong和;
  • 两个实例都不存在值;或者
  • 当前值通过==彼此为“equal to”。

用法:


public boolean equals(Object obj)

参数:此方法接受obj,它是要测试是否相等的对象。

返回值:如果另一个对象是“equal to”,则此方法返回true;否则返回false。

以下示例程序旨在说明equals(Object obj)方法:

示例1:

// Java program to demonstrate 
// OptionalLong.equals(Object obj) method 
  
import java.util.OptionalLong; 
  
public class GFG { 
  
    public static void main(String[] args) 
    { 
  
        // Create first OptionalLong object 
        OptionalLong opLong1 
            = OptionalLong.of(45213246); 
  
        System.out.println("OptionalLong 1: "
                           + opLong1.toString()); 
  
        // Create second OptionalLong object 
        OptionalLong opLong2 
            = OptionalLong.of(45213246); 
  
        System.out.println("OptionalLong 2: "
                           + opLong2.toString()); 
  
        // Check if these two objects are equal 
        // using equals(Object obj) 
        System.out.println("Are both objects equal: "
                           + opLong1.equals(opLong2)); 
    } 
}
输出:
OptionalLong 1: OptionalLong[45213246]
OptionalLong 2: OptionalLong[45213246]
Are both objects equal: true

示例2:

// Java program to demonstrate 
// OptionalLong.equals(Object obj) method 
  
import java.util.OptionalLong; 
  
public class GFG { 
  
    public static void main(String[] args) 
    { 
        // Create first OptionalLong object 
        OptionalLong opLong1 
            = OptionalLong.of(317946492); 
  
        System.out.println("OptionalLong 1: "
                           + opLong1.toString()); 
  
        // Create second OptionalLong object 
        OptionalLong opLong2 
            = OptionalLong.of(45213246); 
  
        System.out.println("OptionalLong 2: "
                           + opLong2.toString()); 
  
        // Check if these two objects are equal 
        // using equals(Object obj) 
        System.out.println("Are both objects equal: "
                           + opLong1.equals(opLong2)); 
    } 
}
输出:
OptionalLong 1: OptionalLong[317946492]
OptionalLong 2: OptionalLong[45213246]
Are both objects equal: false

参考文献: https://docs.oracle.com/javase/10/docs/api/java/util/OptionalLong.html#equals?(Object obj)



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 OptionalLong equals() method in Java with examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。