本示例说明如何使用CompareToBuilder该类自动创建compareTo(Object o)方法的实现。请记住,在实现此方法时,还需要equals(Object o)一致地实现该方法。这将确保您的类的行为与集合排序过程相关。
package org.nhooo.example.commons.lang; import org.apache.commons.lang3.builder.CompareToBuilder; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; public class Fruit implements Comparable<Fruit> { private String name; private String colour; public Fruit(String name, String colour) { this.name = name; this.colour = colour; } public String getName() { return name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Fruit fruit = (Fruit) o; return new EqualsBuilder() .append(name, fruit.name) .append(colour, fruit.colour) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder() .append(name) .append(colour) .toHashCode(); } /* * Generating compareTo() method using CompareToBuilder class. For other * alternative way we can also use the CompareToBuilder.reflectionCompare() * method to implement the compareTo() method. */ public int compareTo(Fruit fruit) { return new CompareToBuilder() .append(this.name, fruit.name) .append(this.colour, fruit.colour) .toComparison(); } }
package org.nhooo.example.commons.lang; public class CompareToBuilderDemo { public static void main(String[] args) { Fruit fruit1 = new Fruit("Orange", "Orange"); Fruit fruit2 = new Fruit("Watermelon", "Red"); if (fruit1.compareTo(fruit2) == 0) { System.out.printf("%s == %s%n", fruit1.getName(), fruit2.getName()); } else { System.out.printf("%s != %s%n", fruit1.getName(), fruit2.getName()); } } }
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency>