Home > DeveloperSection > Forums > Is ArrayList change its hashcode after insert the data?
Jayden Bell
Jayden Bell

Total Post:105

Points:739
Posted on    December-20-2015 11:23 PM

 Java Java  Array List 
Ratings:


 1 Reply(s)
 230  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);
        System.out.println(a.hashCode());
        a.add(1, 2);
        System.out.println(a.hashCode());
    }
}
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?


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Supported
Posted on    December-21-2015 12:19 AM

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.

Don't want to miss updates? Please click the below button!

Follow MindStick