How do I use CompareToBuilder class?

Category: commons.lang, viewed: 3976 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();
    }
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Uncensored Newsgroups
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Java Training

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats