Do I need the equals and Hashcode method if my class implements comparable in Java?

I found this comment for can StringBuffer objects be keys in a TreeSet in Java?

"There are two identification strategies used with Maps in Java (more or less).

Hashing: the input "Foo" is converted to the best possible attempt to generate a number that uniquely accesses the index in the array. (Purists, please do not abuse me, I deliberately simplify). This index stores your value. The probable likelihood that "Foo" and "Bar" will actually generate the same index value, meaning that they will both be mapped to the same position. Obviously, this will not work either where the equals () method comes in; it is used to disambiguate

Comparison Using the comparative method, you do not need this extra step of value because the comparison NEVER produces this collision in the first place. The only key that "Foo" is equal to "Foo". A really good idea, though, if you can, define "equals ()" as compareTo () == 0; for consistency. This is not a requirement.

my question is this: if my class implements comparable values, does this mean that I do not need to override the equals and hashcode methods to use my objects as keys in Hash collections. eg,

class Person implements Comparable<Person> { 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; } } 

Now, is it possible to use Person objects in Hashable collections?

+6
source share
5 answers

The article you are reading is talking about TreeSet . set of trees - this tree with each node has a place defined by this value, compared to other values โ€‹โ€‹already specified in the tree.

a hashTable stores key / value pairs in a hash table. When using a Hashtable, you specify the object that is used as the key, and the value that you want to associate with this key. Then the key is hashed, and the resulting hash code is used as an index in which the value is stored in the table.

the difference between Hashable and TreeSet is that the treeet doesnโ€™t need hashCode , you just need to know if you need to take the element left or right in the tree. for this you can use Compare and nothing more.

in hashTable comparison will be sufficient, because it builds differently, each object falls into its cell, hashing it, and not comparing it with elements that are already in the collection.

so the answer is no, you can use Person in the hash table only with compareTo . u must override hashCode() and equals() for this

I also suggest you read this article about hashtables

+6
source

HashTable uses equals and hashCode values. Each class has these methods. If you do not implement them, you inherit them.

If you need to implement them depends on whether the legacy version is suitable for your purposes. In particular, since Person does not have the specified superclass, it inherits the Object methods. This means that the Person object is equal only to itself.

Do you need two different Person objects that will be considered equal to HashTable keys?

+2
source

if my class implements comparable values, does this mean that I do not need to override the equals and hashcode method to use my objects as keys in Hash collections. eg,

No, you still need to implement equals() and hashCode() . Methods perform very different functions and cannot be replaced with compareTo() .

  • equals() returns a boolean based on the equality of an object. This is usually equality of identity, not field equality. This can be very different from the fields used to compare the object in compareTo(...) , although if it makes sense to the entity, the equals() method can be:

     @Overrides public boolean equals(Object obj) { if (obj == null || obj.getClass() != getClass()) { return false; } else { return compareTo((Person)obj) == 0; } } 
  • hashCode() returns the integer value for the instance that is used in the hash tables to calculate the bucket into which it should be placed. There is no equivalent way to get this value from compareTo(...) .

+1
source

A TreeSet must be mapped to add values โ€‹โ€‹to the right or left of the tree. HashMap needs the equals () and Hashcode () methods available from the object class, but you must override them for your purpose.

0
source

If a class implements Comparable , this assumes that instances of the class represent values โ€‹โ€‹of some type; generally, when classes encapsulate values, two different instances can exist that have the same value and therefore should be considered equivalent. Since the only equivalent for individual instances of objects is their redefinition of equals and hashCode , this means that things that implement Comparable should override equals and hashCode , unless the encapsulated values โ€‹โ€‹by which compare operations are globally unique (assuming that individual instances will never shall be deemed equivalent).

As a simple example, suppose the class includes a CreationRank field of type long ; each time an instance is created, this member is set to a value selected from a singleton AtomicLong , and Comparable uses this field to rank objects in the order they were created. No two different class instances ever report the same CreationRank ; therefore, the only way x.equals(y) should be true if x and y are on the same instance of the object โ€” exactly the way equals and hashCode work by default.

BTW having x.compare(y) zero in return, it usually follows that x.equals(y) will return true, and vice versa, but there are times when x.equals(y) can be false, but x.compare(y) must nonetheless return zero. This may be the case when an object encapsulates some properties that can be ranked, and others that cannot. Consider, for example, the hypothetical FutureAction type, which encapsulates a DateTime and an implementation of the DoSomething interface. Such things can be ranked based on encapsulated dates and times, but there can be no sensible way to rank two elements that have the same date and time but different actions. Having the equals message false, and compare reports that zero will make more sense than pretending that explicitly nonequivalent elements should be called "equal."

0
source

Source: https://habr.com/ru/post/952321/


All Articles