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


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


Instant类的equals(Object otherInstant)方法用于将此Instant与作为参数传递的Instant对象进行比较。两种情况之间的比较是基于瞬间的时间线位置。该方法要返回的值确定如下:

  • 如果两个实例相等,则返回true
  • 如果两个实例不相等,则返回false。

用法:

public boolean equals(Object otherInstant)

参数:此方法接受强制参数otherInstant,该参数是要比较的另一个瞬间,并且不应为null。


返回值:此方法返回一个布尔值,如下所示:

  • 真正:如果两个实例相等。
  • :如果两个实例不相等。

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

示例1:当两个实例相等时

// Java program to demonstrate 
// Instant.equals() method 
  
import java.time.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create two instance objects 
        Instant instant1 
            = Instant.parse("2018-10-20T16:55:30.00Z"); 
  
        Instant instant2 
            = Instant.parse("2018-10-20T16:55:30.00Z"); 
  
        // print Instant Values 
        System.out.println("Instant1: "
                           + instant1); 
        System.out.println("Instant2: "
                           + instant2); 
  
        // compare both instant 
        boolean value = instant1.equals(instant2); 
  
        // print results 
        System.out.println("Are both instants are equal: "
                           + value); 
    } 
}
输出:
Instant1: 2018-10-20T16:55:30Z
Instant2: 2018-10-20T16:55:30Z
Are both instants are equal: true

示例2:当两个实例不相等时

// Java program to demonstrate 
// Instant.equals() method 
  
import java.time.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create two instance objects 
        Instant instant1 
            = Instant.parse("2018-10-20T16:55:30.00Z"); 
  
        Instant instant2 
            = Instant.parse("2011-10-20T16:55:30.00Z"); 
  
        // print Instant Values 
        System.out.println("Instant1: "
                           + instant1); 
        System.out.println("Instant2: "
                           + instant2); 
  
        // compare both instant 
        boolean value = instant1.equals(instant2); 
  
        // print results 
        System.out.println("Are both instants are equal: "
                           + value); 
    } 
}
输出:
Instant1: 2018-10-20T16:55:30Z
Instant2: 2011-10-20T16:55:30Z
Are both instants are equal: false

参考: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#equals(java.lang.Object)



相关用法


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