This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
Perhaps you need to rethink what your application is doing, and what you want it to do.
As Christophe mentions, the Comparable interface allows you to define how you want your objects to be compared, which is usually used when sorting instances of your objects. Your class implements Comparable with the following method:
This basically states that whenever you are comparing two instances of Collection1, you are only interested in what the value is within the c instance variable. Since c is an Integer, and the Integer class implements the Comparable interface, your ArrayList will be sorted according to the natural sort order of Integers.
(A side effect of your using the Integer compareTo method is that you do not really need to override the equals or the hashCode methods. Which is just as well, as there is a bug in your equals method where o can only be null at line 14).
Not necessarily. You can use it anytime you have objects that you want to compare that you want to specify how the comparison works.
You used the example above of having various Collection1 objects inserted into a List, and having them sort by the numerical value of the internal variable 'c' - a perfectly reasonable usage.
In exactly the same way, you might want to have a class that contains a person's name and country (extremely simplified example):
In such a case, you might want to have sort order determined by lastName then firstName, except when the country entered is one of the countries that has family name first. This could give me a sorted list such as:
Last, First, Country
Abrahams, John, England
Shen, Fox, China
Johanson, Donald, USA
As you can see, I want Mr Fox from China sorted between Mr Abrahams from England and Mr Johanson from USA, even though a "standard" sort based on the name in the "first-name" field does not work.
Another example might be when you want to compare currencies. Which is the greater sum: $ 0.50 USD, or ¥ 30 JPY ? If you must keep the original currency, then you probably want to have a specialized comparator behind the scenes to handle the comparison since you cannot just compare the numbers directly.
author and jackaroo