Hashcode - Equals and HashMapHashSet

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

if I override the equals method in the model class and return always false. and the hashCode always returns a constant value. if I create a Object and add it to Set how HashSet/HashMAp detects duplicates?

public class Employee {

   int id;
   String name;
   @Override
   equals(){ 
   return false;
       }
   }

       public static void main(String[] args) {

          HashMap<Employee,String> hk= new HashMap<Employee,String>();
          Employee e1 = new Employee();
          e1.setId(18);
          e1.setName("roohi");
          hk.put(e1, "hello");
          hk.put(e1, "hello");
          }

if the Equals method returns false i.e e1.equals(e1) returns false. so the values should be added twice but its only added one. Can anyone please explain this. I googled and cleared my concept on HashCode and equals contract but here I am failing.

Answers

If you take close look Map.put method

public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key);
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

if you notice this line of code

 if (e.hash == hash && ((k = e.key) == key || key.equals(k)))

though you have overridden equal method but still (k = e.key) == key evaluates to true and it overwrites the old entry.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/41761495/equals-and-hashmap-hashset

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils