Java ArrayList of ArrayList

后端 未结 4 1727
夕颜
夕颜 2020-12-08 02:15

The following code outputs

[[100, 200, 300], [100, 200, 300]]. 

However, what I expect is

[[100, 200, 300], [100, 200]], 
         


        
4条回答
  •  囚心锁ツ
    2020-12-08 03:06

    You are adding a reference to the same inner ArrayList twice to the outer list. Therefore, when you are changing the inner list (by adding 300), you see it in "both" inner lists (when actually there's just one inner list for which two references are stored in the outer list).

    To get your desired result, you should create a new inner list :

    public static void main(String[] args) {
        ArrayList> outer = new ArrayList>();
        ArrayList inner = new ArrayList();        
    
        inner.add(100);     
        inner.add(200);
        outer.add(inner); // add first list
        inner = new ArrayList(inner); // create a new inner list that has the same content as  
                                               // the original inner list
        outer.add(inner); // add second list
    
        outer.get(0).add(300); // changes only the first inner list
    
        System.out.println(outer);
    }
    

提交回复
热议问题