Originally posted by David Dickinson:
I've started reading about the comparable interface and since this will be the first interface i've ever implemented im having a bit of a play with the functionality.
I like the idea of implementing comparable within the existing class but am slightly confused as to how this would compare two objects?
Would ObjectA.Compare(ObjectA,ObjectB) do the job?
Also why should I overide equals? If I don't override it will it never return a 0 from the compare method?
Notice that there are two possible interfaces to use: Comparator or Comparable. Comparator defines the method compare(Object o1, Object o2). Notice that this takes two objects to compare. Comparable on the other hand defines the method compareTo(Object o). Notice this only takes a single object to compare. "So what do I compare it with?" you may ask. You should compare it with "this" (i.e. the "current" object that the method is called on) by calling objA.compare(objB).
Since you want to implement this within the existing class, I think Comparable makes more sense than Comparator. Typically I think of Comparator when you want to implement separate classes for different types of comparisons (e.g. reverse order, case-insensitive
String comparisions, etc.).
Finally, you should probably also override equals() in order to define what it means for two objects to be equal. If you don't, it *is* still possible for compare() to return 0, since Object provides a default implementation of the equals() method. However, this will only happen if the two references being compared point to the exact same object.
Several people here have suggested that you "take a look at the Xxx class." In case you don't know where to look, probably the best reference is
(As a side note classes and interfaces names start with upper case while variable and method names start with lower case.)
the Java API docs. While these docs are not a tutorial, they are very helpful when you need to know how to use a particular class or interface. All of the methods that are available are listed, as well as detailed descriptions. For example, you can easily find the details about Object's default implementation of the equals() method.
I hope this helps. Please come back with more questions.
Keep Coding!
Layne
p.s. Note that convention dictates that class and interface names start start with upper case while variable and method names start in lower case.