Java ArrayList 的 ArrayList [英] Java ArrayList of ArrayList

查看:32
本文介绍了Java ArrayList 的 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码输出

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

然而,我期望的是

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

我哪里错了?

public static void main(String[] args) {
    ArrayList<ArrayList<Integer>> outer = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> inner = new ArrayList<Integer>();        

    inner.add(100);     
    inner.add(200);

    outer.add(inner);
    outer.add(inner);

    outer.get(0).add(300);

    System.out.println(outer);

}

推荐答案

您要将同一个内部 ArrayList 的引用添加到外部列表两次.因此,当您更改内部列表(通过添加 300)时,您会在两个"内部列表中看到它(实际上只有一个内部列表,其两个引用存储在外部列表中).

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<ArrayList<Integer>> outer = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> inner = new ArrayList<Integer>();        

    inner.add(100);     
    inner.add(200);
    outer.add(inner); // add first list
    inner = new ArrayList<Integer>(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);
}

这篇关于Java ArrayList 的 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆