java.time包中ZoneOffset類的compareTo(ZoneOffset)方法用於比較作為參數傳遞給此ZoneOffset實例的ZoneOffset的另一個實例。此方法返回一個整數值,該整數值是比較器值。
用法:
public int compareTo(ZoneOffset anotherZoneOffset)
參數:此方法接受要與該ZoneOffset實例進行比較的參數anotherZoneOffset。
返回值:此方法返回一個整數值,如下所示:
- 如果此實例大於作為參數傳遞的實例,則返回正值
- 如果此實例等於作為參數傳遞的實例,則返回零(0)
- 如果此實例小於作為參數傳遞的實例,則返回負值。
異常:如果作為參數傳遞的anotherZoneOffset為null,則此方法引發NullPointerException。
以下示例說明了ZoneOffset.compareTo()方法:
示例1:
// Java code to illustrate compareTo() method
import java.time.*;
public class GFG {
public static void main(String[] args)
{
// Get the ZoneOffset instance
ZoneOffset zoneOffset1
= ZoneOffset.ofHours(5);
System.out.println("ZoneOffset 1: "
+ zoneOffset1);
// Get the ZoneOffset instance
ZoneOffset zoneOffset2
= ZoneOffset.ofHours(5);
System.out.println("ZoneOffset 2: "
+ zoneOffset2);
// Get the ZoneOffset instance
ZoneOffset zoneOffset3
= ZoneOffset.ofHours(3);
System.out.println("ZoneOffset 3: "
+ zoneOffset3);
// Using compareTo() method
System.out.println("ZoneOffset 1 "
+ "compared to ZoneOffset 2: "
+ zoneOffset1.compareTo(zoneOffset2));
// Using compareTo() method
System.out.println("ZoneOffset 1 "
+ "compared to ZoneOffset 3: "
+ zoneOffset1.compareTo(zoneOffset3));
// Using compareTo() method
System.out.println("ZoneOffset 3 "
+ "compared to ZoneOffset 1: "
+ zoneOffset3.compareTo(zoneOffset1));
}
}
輸出:
ZoneOffset 1: +05:00 ZoneOffset 2: +05:00 ZoneOffset 3: +03:00 ZoneOffset 1 compared to ZoneOffset 2: 0 ZoneOffset 1 compared to ZoneOffset 3: -7200 ZoneOffset 3 compared to ZoneOffset 1: 7200
示例2:顯示NullPointerException
// Java code to illustrate compareTo() method
import java.time.*;
public class GFG {
public static void main(String[] args)
{
try {
// Get the ZoneOffset instance
ZoneOffset zoneOffset
= ZoneOffset.ofHours(3);
System.out.println("ZoneOffset: "
+ zoneOffset);
// Using compareTo() method
System.out.println("ZoneOffset "
+ "compared to null: ");
zoneOffset.compareTo(null);
}
catch (Exception e) {
System.out.println(e);
}
}
}
輸出:
ZoneOffset: +03:00 ZoneOffset compared to null: java.lang.NullPointerException
參考: Oracle Doc
相關用法
- Java ZoneOffset systemDefault()用法及代碼示例
- Java ZoneOffset getRules()用法及代碼示例
- Java ZoneOffset of(String)用法及代碼示例
- Java ZoneOffset ofHoursMinutes(int, int)用法及代碼示例
- Java ZoneOffset from(TemporalAccessor)用法及代碼示例
- Java ZoneOffset ofTotalSeconds(int)用法及代碼示例
- Java ZoneOffset ofOffset()用法及代碼示例
- Java ZoneOffset get(TemporalField)用法及代碼示例
- Java ZoneOffset ofHours(int)用法及代碼示例
- Java ZoneOffset getAvailableZoneIds()用法及代碼示例
- Java ZoneOffset getDisplayName()用法及代碼示例
- Java ZoneOffset normalized()用法及代碼示例
- Java ZoneOffset hashCode()用法及代碼示例
- Java ZoneOffset getId()用法及代碼示例
- Java ZoneOffset getTotalSeconds()用法及代碼示例
注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 ZoneOffset compareTo(ZoneOffset) method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。