通常情况下,在日常工作中咱使用的比较方式有两种:
a、通过比较器比较
b、通过比较运算符比较
当我们比较对象的时候,guava官网也对此举例说明如下:
image.png借助翻译软件,大致意思如下😄:
这段代码很容易出错,难以扫描错误,而且冗长得令人不快。我们应该能做得更好。
因此,在guava的集合包下提供了ComparisonChain类,支持引用类型以及Comparable比较,简单使用如下:
public static void main(String[] args) {
Integer numberLeft = 1;
Integer numberRight = 2;
System.out.println("=========测试左边小右边大========");
System.out.println(ComparisonChain.start().compare(numberLeft, numberRight,Ordering.natural().nullsLast()).result());
System.out.println("=========测试左边大右边小========");
System.out.println(ComparisonChain.start().compare(numberRight, numberLeft).result());
System.out.println("=========测试左右相等========");
System.out.println(ComparisonChain.start().compare(numberRight, numberRight).result());
System.out.println("=============compareFalseFirst==================");
//注意参数不能为null,否则会出现npe
Boolean booleanLeft = true;
Boolean booleanRight = false;
System.out.println("=========测试左边true右边false========");
System.out.println(ComparisonChain.start().compareFalseFirst(booleanLeft, booleanRight).result());
System.out.println("=========测试左边false右边true========");
System.out.println(ComparisonChain.start().compareFalseFirst(booleanRight, booleanLeft).result());
System.out.println("=========测试左右相等false========");
System.out.println(ComparisonChain.start().compareFalseFirst(booleanRight, booleanRight).result());
System.out.println("=========测试左右相等true========");
System.out.println(ComparisonChain.start().compareFalseFirst(booleanLeft, booleanLeft).result());
System.out.println("===============compareTrueFirst================");
System.out.println("=========测试左边true右边false========");
System.out.println(ComparisonChain.start().compareTrueFirst(booleanLeft, booleanRight).result());
System.out.println("=========测试左边false右边true========");
System.out.println(ComparisonChain.start().compareTrueFirst(booleanRight, booleanLeft).result());
System.out.println("=========测试左右相等false========");
System.out.println(ComparisonChain.start().compareTrueFirst(booleanRight, booleanRight).result());
System.out.println("=========测试左右相等true========");
System.out.println(ComparisonChain.start().compareTrueFirst(booleanLeft, booleanLeft).result());
//多个compare的时候,result结果为第一个compare的结果
System.out.println(ComparisonChain.start().compare(numberLeft, numberRight).compare(numberRight,numberLeft).result());
}
网友评论