Note that there are some explanatory texts on larger screens.

plurals
  1. PODo I need a equals and Hashcode method if my class implements comparable in Java?
    primarykey
    data
    text
    <p>I found this comment on <a href="https://stackoverflow.com/questions/18389298/can-stringbuffer-objects-be-keys-in-treeset-in-java">can StringBuffer objects be keys in TreeSet in Java?</a></p> <p>"There are 2 identifying strategies used with Maps in Java (more-or-less).</p> <p>Hashing: An input "Foo" is converted into a best-as-possible attempt to generate a number that uniquely accesses an index into an array. (Purists, please don't abuse me, I am intentionally simplifying). This index is where your value is stored. There is the likely possibility that "Foo" and "Bar" actually generate the same index value meaning they would both be mapped to the same array position. Obviously this can't work and so that's where the "equals()" method comes in; it is used to disambiguate</p> <p>Comparison: By using a comparative method you don't need this extra disambiguation step because comparison NEVER produces this collision in the first place. The only key that "Foo" is equal to is "Foo". A really good idea though is if you can is to define "equals()" as compareTo() == 0; for consistency sake. Not a requirement."</p> <p>my question is as follows: if my class implements comparable, then does it mean I dont have to override equals and hashcode method for using my objects as keys in Hash collections. eg</p> <pre><code>class Person implements Comparable&lt;Person&gt; { int id; String name; public Person(int id, String name) { this.id=id; this.name=name; } public int compareTo(Person other) { return this.id-other.id; } } </code></pre> <p>Now, can I use my Person objects in Hashable collections?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload