Java ArrayList of ArrayList

后端 未结 4 1737
夕颜
夕颜 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:12

    The command outer.add(inner) adds a reference to inner, not a copy of it.

    So, when you add two references to inner to the ArrayList outer, you're adding two of the same thing. Modifying inner through outer.get(0) also modifies the value in outer.get(1), because they refer to the same thing.

    If you create a copy of inner and use that instead, then you'll have two different instances and be able to modify them separately. You can do this with a simple command:

    outer.add(new ArrayList<[var type]>(inner));
    

    The instruction for new ArrayList(inner) creates a new ArrayList with the contents of inner inside of it - but doesn't use the same instance as inner. Thus, you'll retain the content, but not retain the duplicated reference.

    By adding the new copy instead of the reference, you can modify the copy without modifying what you might call the "original."

提交回复
热议问题