Why does one arraylist change when a copy of it is modified

后端 未结 6 1727
傲寒
傲寒 2020-12-11 08:52

Its probably a very simple one but its\' still confusing me!

import java.util.ArrayList;

public class Sample {
    ArrayList i = new ArrayLis         


        
6条回答
  •  眼角桃花
    2020-12-11 09:27

    Let me do this in the following way for you:

    ArrayList i = new ArrayList<>();
    ArrayList j = new ArrayList<>();
    
    // checking hash code before j = i;
    System.out.println(System.identityHashCode(i));
    System.out.println(System.identityHashCode(j));
    
    j = i;
    
    // checking hash code after j = i;
    System.out.println(System.identityHashCode(i));
    System.out.println(System.identityHashCode(j));
    

    compare both the values if they are same that means after j=i; ArrayList j is now pointing to ArrayList i

    In my machine o/p was:

    30269696 //hashCode of i
    24052850 //hashCode of j before j = i;
    
    30269696 //hashCode of i and j are same after j = i that means they are pointing to same reference and hence change in one reflects on the other.
    30269696
    

提交回复
热议问题