Java中Year類的compareTo()方法用於將Year對象與另一個Year對象進行比較。 Year對象的比較基於Year的值。
用法:
public int compareTo(Year otherYear)
參數:此方法接受單個參數otherYear。是Year對象,它指定要與當前Year對象進行比較的年份。
返回值:它基於兩個Year對象的比較返回一個整數比較器值。
以下程序說明了Java中Year的compareTo()方法:
示例1::在此程序中,當前Year對象的值小於第二年對象。因此,返回的值為-1。
// Program to illustrate the compareTo() method
import java.util.*;
import java.time.*;
public class GfG {
public static void main(String[] args)
{
// Creates first Year object
Year firstYear = Year.of(2017);
// Creates second year object
Year secondYear = Year.of(2018);
// Compare the two years and print the
// comparator value
System.out.println(firstYear.compareTo(secondYear));
}
}
輸出:
-1
示例2::在此程序中,當前Year對象的值等於第二年對象。因此,返回的值為0。
// Program to illustrate the compareTo() method
import java.util.*;
import java.time.*;
public class GfG {
public static void main(String[] args)
{
// Creates first Year object
Year firstYear = Year.of(2018);
// Creates second year object
Year secondYear = Year.of(2018);
// Compare the two years and print the
// comparator value
System.out.println(firstYear.compareTo(secondYear));
}
}
輸出:
0
參考: https://docs.oracle.com/javase/8/docs/api/java/time/Year.html#compareTo-java.time.Year-
相關用法
- Java OffsetTime compareTo()用法及代碼示例
- Java DoubleBuffer compareTo()用法及代碼示例
- Java UUID compareTo()用法及代碼示例
- Java Float compareTo()用法及代碼示例
- Java ByteBuffer compareTo()用法及代碼示例
- Java OffsetDateTime compareTo()用法及代碼示例
- Java Calendar compareTo()用法及代碼示例
- Java LocalDateTime compareTo()用法及代碼示例
- Java ChronoLocalDateTime compareTo()用法及代碼示例
- Java FloatBuffer compareTo()用法及代碼示例
- Java Instant compareTo()用法及代碼示例
- Java ShortBuffer compareTo用法及代碼示例
- Java ChronoZonedDateTime compareTo()用法及代碼示例
- Java Path compareTo()用法及代碼示例
- Java Short compareTo()用法及代碼示例
注:本文由純淨天空篩選整理自barykrg大神的英文原創作品 Year compareTo() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。