Java中的 ZoneOffset compareTo(ZoneOffset) 方法及示例
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 文档