Java中的 OptionalDouble equals() 方法及示例
OptionalDouble帮助我们创建一个可能包含也可能不包含 Double 值的对象。 equals(Object obj)方法帮助我们将此 OptionalDouble 对象与作为参数传递的对象进行比较,如果对象相等,则返回 true。
如果满足以下条件,则认为另一个对象等于此 OptionalDouble:
- 它也是一个 OptionalDouble 并且;
- 两个实例都没有价值,或者;
- 当前值通过 == 彼此“相等”。
句法:
public boolean equals(Object obj)
参数:此方法接受一个obj ,它是要测试是否相等的对象。
返回值:如果另一个对象“等于”这个对象,则此方法返回 true,否则返回 false。
下面的程序说明了 equals(Object obj) 方法:
方案一:
// Java program to demonstrate
// OptionalDouble.equals(Object obj) method
import java.util.OptionalDouble;
public class GFG {
public static void main(String[] args)
{
// Create first OptionalDouble object
OptionalDouble opDouble1
= OptionalDouble.of(452.13246);
System.out.println("OptionalDouble 1: "
+ opDouble1.toString());
// Create second OptionalDouble object
OptionalDouble opDouble2
= OptionalDouble.of(452.13246);
System.out.println("OptionalDouble 2: "
+ opDouble2.toString());
// Check if these two objects are equal
// using equals(Object obj)
System.out.println("Are both objects equal: "
+ opDouble1.equals(opDouble2));
}
}
输出:
OptionalDouble 1: OptionalDouble[452.13246]
OptionalDouble 2: OptionalDouble[452.13246]
Are both objects equal: true
方案二:
// Java program to demonstrate
// OptionalDouble.equals(Object obj) method
import java.util.OptionalDouble;
public class GFG {
public static void main(String[] args)
{
// Create first OptionalDouble object
OptionalDouble opDouble1
= OptionalDouble.of(3179464.92);
System.out.println("OptionalDouble 1: "
+ opDouble1.toString());
// Create second OptionalDouble object
OptionalDouble opDouble2
= OptionalDouble.of(4521.3246);
System.out.println("OptionalDouble 2: "
+ opDouble2.toString());
// Check if these two objects are equal
// using equals(Object obj)
System.out.println("Are both objects equal: "
+ opDouble1.equals(opDouble2));
}
}
输出:
OptionalDouble 1: OptionalDouble[3179464.92]
OptionalDouble 2: OptionalDouble[4521.3246]
Are both objects equal: false
参考资料: https: Java/util/OptionalDouble.html#equals?(Object obj)