持续时间类compareTo()方法 (Duration Class compareTo() method)
compareTo() method is available in java.time package.
compareTo()方法在java.time包中可用。
compareTo() method is used to compare this Duration object to the given object.
compareTo()方法用于将此Duration对象与给定对象进行比较。
compareTo() method is a non-static method, it is accessible with class object only and if we try to access the method with class name then we will get an error.
compareTo()方法是一个非静态方法,只能通过类对象访问,如果尝试使用类名访问该方法,则会收到错误消息。
compareTo() method does not throw an exception at the time of comparing.
compareTo()方法在比较时不会引发异常。
Syntax:
句法:
public int compareTo(Duration d);
Parameter(s):
参数:
Duration d – represents the object to be compared to this Duration object.
持续时间d –表示要与此持续时间对象进行比较的对象。
Return value:
返回值:
The return type of this method is int, it may return anyone of the given values.
此方法的返回类型为int ,它可以返回任何给定值。
When (this Duration) == (Duration d), it returns 0.
当(this Duration)==(Duration d)时,它返回0。
When (this Duration) < (Duration d), it returns -1.
当(this Duration)<(Duration d)时,它返回-1。
When (this Duration) > (Duration d), it returns 1.
当(this Duration)>(Duration d)时,返回1。
Example:
例:
// Java program to demonstrate the example
// of int compareTo() method of Duration
import java.time.*;
import java.time.temporal.*;
public class CompareToOfDuration {
public static void main(String args[]) {
// Instantiates three Duration objects
Duration du1 = Duration.ofHours(2);
Duration du2 = Duration.ofMinutes(2);
Duration du3 = Duration.between(LocalTime.MIN, LocalTime.MAX);
System.out.println("du1: " + du1);
System.out.println("du2: " + du2);
System.out.println("du3: " + du3);
System.out.println();
// compares this Duration object(du1)
// to the given Duration object(du2) i.e here
// it returns 1 because the value of du1>du2
int compare = du1.compareTo(du2);
System.out.println("du1.compareTo(du2): " + compare);
// compares this Duration object(du2)
// to the given Duration object(du1) i.e here
// it returns -1 because the value of du2<du1
compare = du2.compareTo(du1);
System.out.println("du2.compareTo(du1): " + compare);
// compares this Duration object(du3)
// to the given Duration object(du3) i.e here
// it returns 0 because the value of du2==du1
compare = du3.compareTo(du3);
System.out.println("du3.compareTo(du3): " + compare);
}
}
Output
输出量
du1: PT2H
du2: PT2M
du3: PT23H59M59.999999999Sdu1.compareTo(du2): 1
du2.compareTo(du1): -1
du3.compareTo(du3): 0
翻译自: https://www.includehelp.com/java/duration-compareto-method-with-example.aspx