可以使用equals()
Java中Period类中的方法确定两个Periods是否相等。此方法需要单个参数,即要比较的Period对象。如果两个Period对象相等,则返回true,否则返回false。
演示此程序如下
import java.time.Period; public class Demo { public static void main(String[] args) { String period1 = "P5Y7M15D"; Period p1 = Period.parse(period1); String period2 = "P5Y7M15D"; Period p2 = Period.parse(period2); System.out.println("The Period p1 is: " + p1); System.out.println("The Period p2 is: " + p2); boolean flag = p1.equals(p2); if(flag) System.out.println("\nBoth Period objects are equal"); else System.out.println("\nBoth Period objects are not equal"); } }
输出结果
The Period p1 is: P5Y7M15D The Period p2 is: P5Y7M15D Both Period objects are equal
现在让我们了解上面的程序。
显示两个期间对象。使用equals()
方法检查Period对象是否相等。使用if语句显示方法的返回值。演示此代码段如下所示:
String period1 = "P5Y7M15D"; Period p1 = Period.parse(period1); String period2 = "P5Y7M15D"; Period p2 = Period.parse(period2); System.out.println("The Period p1 is: " + p1); System.out.println("The Period p2 is: " + p2); boolean flag = p1.equals(p2); if(flag) System.out.println("\nBoth Period objects are equal"); else System.out.println("\nBoth Period objects are not equal");