Why does the hashCode() of an ArrayList change every time you add a new element?

后端 未结 2 1185
难免孤独
难免孤独 2021-02-05 08:21

As per my understanding of ArrayList, the default capacity is 10 and when it grows beyond 10, it will create a new object with new capacity and so on..

So o

相关标签:
2条回答
  • 2021-02-05 08:27

    The hashCode of List implementations is defined in terms of the hashCode of its elements. This means that for ArrayList to be a conforming List implementation it's hashCode must change when its content changes.

    More generally: for mutable objects, the hashCode should change whenever they change in a way that would make them not equal to their previous state.

    You seem to be assuming that it uses the default hashCode of Object, which is not the case.

    Additionally, even if ArrayList did not implement hashCode, the default hash code (also known as the identity hash code) of an ArrayList would not change if the internal array was re-allocated, as the ArrayList object itself stays the same, just the internal array object (that you don't get direct access to) will be replaced with a new one.

    0 讨论(0)
  • 2021-02-05 08:37

    The hashCode of ArrayList is a function of the hashCodes of all the elements stored in the ArrayList, so it doesn't change when the capacity changes, it changes whenever you add or remove an element or mutate one of the elements in a way that changes its hashCode.

    Here's the Java 8 implementation (it's actually implemented in AbstractList) :

    public int hashCode() {
        int hashCode = 1;
        for (E e : this)
            hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
        return hashCode;
    }
    

    BTW, this is the exact code that appears in the Javadoc of hashCode() of the List interface :

    int java.util.List.hashCode()

    Returns the hash code value for this list. The hash code of a list is defined to be the result of the following calculation:

    int hashCode = 1;
    for (E e : list)
        hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
    
    0 讨论(0)
提交回复
热议问题