How do I use CompareToBuilder class?
Category: Commons Lang, viewed: 691 time(s).
This example show how we can use the CompareToBuilder class for automatically create an implementation of compareTo(Object o) method. Please remember when you implementing this method you will also need to implement the equals(Object o) method consistently. This will make sure the behavior of your class consistent in relation to collections sorting process.
package org.kodejava.example.commons.lang; import org.apache.commons.lang.builder.CompareToBuilder; public class CompareToExample { public static void main(String[] args) { Fruit orange = new Fruit("Orange", "Orange"); Fruit watermelon = new Fruit("Watermelon", "Red"); if (orange.compareTo(watermelon) == 0) { System.out.println(orange.getName() + " == " + watermelon.getName()); } else { System.out.println(orange.getName() + " != " + watermelon.getName()); } } } class Fruit { private String name; private String colour; public Fruit(String name, String colour) { this.name = name; this.colour = colour; } public String getName() { return name; } /* * Generating compareTo() method using CompareToBuilder class. For other * alternative way we can also use the reflectionCompare() method to * implement the compareTo() method. */ public int compareTo(Object o) { Fruit f = (Fruit) o; return new CompareToBuilder() .append(this.name, f.name) .append(this.colour, f.colour) .toComparison(); } } |
Can't find what you are looking for? Join our FORUMS and ask some questions!
Related Examples
- How do I find text between two strings?
- How do I check for an empty string?
- How do I get the nearest hour, minute, second of a date?
- How do I format date and time using DateFormatUtils class?
- How do I find items in an array?
- How do I use ReflectionToStringBuilder class?
- How do I convert array of object to array of primitive?
- How do I convert an array to a Map?
- How do I reverse array elements order?
- How do I count word occurrences in a string?