Java Period equals()方法及示例

来源:这里教程网 时间:2026-02-17 21:05:38 作者:

Java Period equals()方法及示例

Java中Period类的equals()方法是用来检查两个给定的周期是否相等。

这种比较是基于Period类型和三个年份、月份和日期中的每一个。要想相等,所有三个年份、月份和日期都必须单独相等。

语法

public boolean equals(Period secondPeriod)

参数: 该方法接受一个参数secondPeriod,它是另一个要比较的时期。

返回值: 如果给定的周期相等,上述方法返回真,否则返回假。

下面的程序说明了上述方法。

程序1 :

// Java code to show the period// equals for two given periodsimport java.time.LocalDate;import java.time.Period;  public class PeriodClass {      // Function to check if two given periods    // are equals or not    static boolean checkIfEqualPeriod(Period firstPeriod,                                      Period secondPeriod)    {          return firstPeriod.equals(secondPeriod);    }      // Driver Code    public static void main(String[] args)    {          // Given period        Period first = Period.ofDays(28);        Period second = Period.ofDays(8);          System.out.println(checkIfEqualPeriod(first, second));    }}

输出:

false

程序2

// Java code to show the period// equals for two given periodsimport java.time.LocalDate;import java.time.Period;  public class PeriodClass {      // Function to check if two given periods    // are equals or not    static boolean checkIfEqualPeriod(Period firstPeriod,                                      Period secondPeriod)    {          return firstPeriod.equals(secondPeriod);    }      // Driver Code    public static void main(String[] args)    {          // Given period        Period first2 = Period.ofDays(28);        Period second2 = Period.ofDays(28);          System.out.println(checkIfEqualPeriod(first2, second2));    }}

输出:

true

参考资料 : https://docs.oracle.com/javase/8/docs/api/java/time/Period.html#equals-java.lang.Object-

相关推荐