Java J2EE Portal
Enterprise Java Station
J2EE curve
Java News / Articles
Java News / Articles
Building Advanced Components For Tapestry Web Applications
Implementing Document Management using the Alfresco Enterprise CMS
Compare Wicket Tapestry JSF Framework
Wicket, Tapestry and JSF side by side
Processing...
Buy Java, Deals On Software Technology Store
Click here for great deals on computers, laptops, software and books
Simplifying Java with Jakarta Commons Lang PDF Print
Written by Harshad Oak   
May 17, 2006 at 11:52 PM
Comparing and Sorting Objects

Having to compare data objects and sort them accordingly is a pretty common requirement. So how do you think we can compare and sort objects of the Computer class we saw in Listing 6?

You guessed it! Let's use Lang to sort Computer objects based on the cost of the computer. To compare objects, you need to implement the java.lang.Comparable interface. This interface has a single method compareTo(Object). The method implementation is expected to compare the current object with the object that is passed to the method. The method returns a negative integer, zero, or a positive integer if this object is less than, equal to, or greater than the specified object.

So to compare Computer objects, implement the compareTo() method in the class Computer, as shown in Listing 8.

Listing 8. A compareTo() method

public int compareTo(Object obj) {
    Computer anotherComputer = (Computer)obj;
    //return new CompareToBuilder().reflectionCompare(this, anotherComputer);
    return new CompareToBuilder().
			append(this.cost, anotherComputer.cost).toComparison();
}

Then, to actually try out the comparison, we write a simple class named ComputerSort, as shown in Listing 9. We just add three objects to an ArrayList and then sort it.

Listing 9. ComputerSort class

public class ComputerSort  {

    public static void main(String[] args) {
        ArrayList computerList = new ArrayList();
        computerList.add(new Computer("Pentium","black", 1000));
        computerList.add(new Computer("Pentium","chocolate", 334));
        computerList.add(new Computer("Pentium","darkgray", 2234));

        Collections.sort(computerList);
        System.out.println(computerList);
    }

}

When we execute ComputerSort, we will see that the objects get sorted by the value of the field cost. The CompareToBuilder like the ToStringBuilder also has a reflection-based usage option. We have commented that bit in the compareTo() method in Listing 8 because in this case the reflection option will compare all fields and get us an incorrect result. CompareToBuilder also has methods that can be used if you not only wish to compare fields in the current class but also its super class. The output on execution of the ComputerSort class is as shown in Listing 10.

Listing 10. Sorted Computer objects

[dev2dev.Computer@cf2c80[processor=Pentium,color=chocolate,cost=334]
, dev2dev.Computer@12dacd1[processor=Pentium,color=black,cost=1000]
, dev2dev.Computer@1ad086a[processor=Pentium,color=darkgray,cost=2234]]

Conclusion

In this article we took a look at some of the key capabilities of the Jakarta Commons Lang component. The Commons project as a whole is a very useful yet underutilized project. While open source projects do use many Commons components, their adoption outside the open source world isn't nearly as widespread. Now that you have an understanding of what Lang has to offer, you should look at adopting it right away. You can also look at the Commons project for useful components that can simplify XML parsing, enable your application to talk HTTP, systematize validations, and perform many other functions.

Download

Download the code used in this article: examples.zip (3KB)

References

Harshad Oak is the creator of the Java J2EE portal IndicThreads.com. He wrote Pro Jakarta Commons and Oracle JDeveloper 10g: Empowering J2EE Development as well as coauthored Java 2 Enterprise Edition 1.4 Bible. He is also the founder of Rightrix Solutions


User Comments
Your Name / Email Address
Comment
Spam Protection - Please enter the code in the image -

Listen to code




Add This Feed Button

Enter your Email


Java Expert Interviews
TitusBrown
Test Driven Development doesn't fit my brain
AndreyGrebnev
Use a spade to dig a hole - Use a bulldozer to dig a trench
TedLeungOpenSource
Why is open source so successful? Why should I contribute to open source?
Processing...
Go to top of page  Home |
SiteMap

Copyright 2004 to 2008 Rightrix Solutions. All rights reserved. All product names are trademarks of their respective companies. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. Rightrix Solutions and IndicThreads.com are independent of Sun Microsystems, Inc.

Views expressed at IndicThreads.com reflect the views of the authors alone, and do not necessarily reflect those of IndicThreads.com. IndicThreads.com and it's authors are not responsible for reader comments and opinions.

Enterprise Java J2EE JEE Portal >> IndicThreads.com