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

后端 未结 2 1186
难免孤独
难免孤独 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: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());
    

提交回复
热议问题