compareTo()

Discussions

General J2EE: compareTo()

  1. compareTo() (1 messages)

    Hi All,

    Can anybody clear this thing for me.When I want to add my own user defined object as a key in hashMap or Hashtable do I need to inlement the compareto() method of Comparable Interface? At the same time is it neccesary to implement hashCode() and equals() method as well?

    Thanks
    Sabyasachi

    Threaded Messages (1)

  2. compareTo()[ Go to top ]

    Hi All,Can anybody clear this thing for me.When I want to add my own user defined object as a key in hashMap or Hashtable do I need to inlement the compareto() method of Comparable Interface?

    Unless you're using a sorted Map (and even then you can supply a Comparator in lieu of implementing a Comparable), no.
    At the same time is it neccesary to implement hashCode() and equals() method as well?ThanksSabyasachi

    It is not necessary, because the equals/hashCode methods you inherit from Object() will work.

    However, the default equals isn't very useful (it doesn't us any of your object fields, for example), so you'll probably want to override it. And when you do that, you should always override hashCode (see Effective Java p.36, Item 8 for a good explanation)