How does a Java HashMap handle different objects with the same hash code?

前端 未结 14 1325
余生分开走
余生分开走 2020-11-22 02:27

As per my understanding I think:

  1. It is perfectly legal for two objects to have the same hashcode.
  2. If two objects are equal (using the equals() method)
14条回答
  •  你的背包
    2020-11-22 03:16

    HashMap structure diagram

    HashMap is an array of Entry objects.

    Consider HashMap as just an array of objects.

    Have a look at what this Object is:

    static class Entry implements Map.Entry {
            final K key;
            V value;
            Entry next;
            final int hash;
    … 
    }
    

    Each Entry object represents a key-value pair. The field next refers to another Entry object if a bucket has more than one Entry.

    Sometimes it might happen that hash codes for 2 different objects are the same. In this case, two objects will be saved in one bucket and will be presented as a linked list. The entry point is the more recently added object. This object refers to another object with the next field and so on. The last entry refers to null.

    When you create a HashMap with the default constructor

    HashMap hashMap = new HashMap();
    

    The array is created with size 16 and default 0.75 load balance.

    Adding a new key-value pair

    1. Calculate hashcode for the key
    2. Calculate position hash % (arrayLength-1) where element should be placed (bucket number)
    3. If you try to add a value with a key which has already been saved in HashMap, then value gets overwritten.
    4. Otherwise element is added to the bucket.

    If the bucket already has at least one element, a new one gets added and placed in the first position of the bucket. Its next field refers to the old element.

    Deletion

    1. Calculate hashcode for the given key
    2. Calculate bucket number hash % (arrayLength-1)
    3. Get a reference to the first Entry object in the bucket and by means of equals method iterate over all entries in the given bucket. Eventually we will find the correct Entry. If a desired element is not found, return null

提交回复
热议问题