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

后端 未结 2 1184
难免孤独
难免孤独 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.

提交回复
热议问题