This example show how we can use the CompareToBuilder
class for automatically create an implementation of compareTo(Object o)
method. Please remember, when you are implementing this method, you will also need to implement the equals(Object o)
method consistently. This will make sure the behavior of your class is consistent in relation to collection sorting processes.
package org.kodejava.commons.lang.support;
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 another
* 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.kodejava.commons.lang;
import org.kodejava.commons.lang.support.Fruit;
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 Dependencies
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.14.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
You have built an NullPointerException in your example.