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


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。