Duration类compareTo()方法
- compareTo() 方法可在
java.time
包。 - compareTo() 方法用于将此 Duration 对象与给定对象进行比较。
- compareTo() 方法是一个非静态方法,它只能通过类对象访问,如果我们尝试使用类名访问该方法,则会出现错误。
- compareTo() 方法比较时不抛出异常。
用法:
public int compareTo(Duration d);
参数:
Duration d
– 表示要与此 Duration 对象进行比较的对象。
返回值:
这个方法的返回类型是int
,它可能返回给定值中的任何一个。
- 当 (this Duration) == (Duration d) 时,返回 0。
- 当 (this Duration) < (Duration d) 时,它返回 -1。
- 当 (this Duration) > (Duration d) 时,返回 1。
例:
// 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);
}
}
输出
du1:PT2H du2:PT2M du3:PT23H59M59.999999999S du1.compareTo(du2):1 du2.compareTo(du1):-1 du3.compareTo(du3):0
相关用法
- Java Duration compareTo(Duration)用法及代码示例
- Java Duration dividedBy()用法及代码示例
- Java Duration minusMillis(long)用法及代码示例
- Java Duration plus(Duration)用法及代码示例
- Java Duration plus(long, TemporalUnit)用法及代码示例
- Java Duration subtractFrom(Temporal)用法及代码示例
- Java Duration toNanosPart()用法及代码示例
- Java Duration subtractFrom()用法及代码示例
- Java Duration toSeconds()用法及代码示例
- Java Duration multipliedBy()用法及代码示例
- Java Duration minusNanos(long)用法及代码示例
- Java Duration minusMinutes(long)用法及代码示例
- Java Duration minusDays(long)用法及代码示例
- Java Duration toMillis()用法及代码示例
- Java Duration ofSeconds(long)用法及代码示例
- Java Duration ofMinutes(long)用法及代码示例
- Java Duration multipliedBy(long)用法及代码示例
- Java Duration plusDays(long)用法及代码示例
- Java Duration addTo()用法及代码示例
- Java Duration toMinutes()用法及代码示例
注:本文由纯净天空筛选整理自 Java Duration Class | compareTo() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。