This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
So I need compare two objects, and I hear that the best way is to use the compareTo method in the Comparable class. I understand how to use it it and the syntax of it. However...... I seem to not understand how to implement it. meaning I can't use it in my program, because the compiler can not find the compareTo method. I have gone to JavaDocs but, I don't really understand all the requirements I must meet. Can someone elaborate? preferably give a basic example?
In what way? Equal/not equal? Then just override and use the equals() method. If you want your class to have a "natural order," then you'd implement Comparable and define compareTo(). Note, however, that unless you're implementing a sort algorithm yourself (e.g. quicksort, mergesort, bubblesort, ...), you'll rarely if ever call compareTo() directly in your code.
I think first of all you have to be clear and specific about the context in which you need to compare objects. I mean whether you want to sort a collection or you want to test the eqality of objects. After that it will be easy to understand which stretegy is required to compare.
By the way "Comparable" is an interface NOT a class which you implement to make your class eligible for comparision during sorting with the help of either Collections.sort() of Arrars.sort().
Collections.sort() is an utility static method to sort a colletion type and Arrays.sort() is for sorting arrays.