Advertise with us

Is ArrayList change its hashcode after insert the data?

Posted by  Jayden Bell
 984  View(s)
Rate this:
I think,  the hashCode() of an object could be the same thing of the object address as in C++, so I expected the hashCode of the object remain the same before and after insert the data.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Hello {
    public static void main(String[] args) {
        List<Integer> a = new ArrayList<>(1024);
        a.add(0, 1);
        a.add(1, 2);
but it seems it output a different value, so which means after insert a value, the new list object is a deep copy value of the original one?
  1. Re: Is ArrayList change its hashcode after insert the data?

    hashCode isn't the object's address, but the calculated hash value of the object's content. Refer to javadoc for more information

    If you want to compare and check if it is the same object then you can use == operator, which checks the reference.

    According to Javadocs , the hashcode of a List will be calculated based on the individual objects hash code in it. So whenever you add an element to the List, this is going to affect the hashCode of the List directly.