【问题标题】:adding a list to an empty list of lists [closed]将列表添加到列表的空列表[关闭]
【发布时间】:2014-05-02 19:24:00
【问题描述】:

如何将列表添加到空列表中?

喜欢:

static int[][] Pos = new int[][2]; //this actually don't work
// list1 = [0, 1]; list2 = [2, 3]
Pos.add(list1); 
Pos.add(list2);

“Pos”应该返回这个:

[[0, 1], [2, 3]]

这怎么可能?

【问题讨论】:

  • 您没有列表列表。
  • 你也需要处理你的语法...[0, 1] 不是有效的 Java。
  • 老兄,听说你喜欢列表...
  • @ElGavilan 所以我把一个列表放到你的列表中,这样你就可以在添加到列表的同时添加到列表
  • @user3580294 实际上,您可以将第二个留空。 int[][] a = new int[2][]; 有效。

标签: java list


【解决方案1】:

从您当前的代码中,您想要初始化一个ints 的数组。

static int[][] Pos = new int[2][];

static {
    int[] array1 = { 0, 1 };
    int array2 = { 2, 3 };
    Pos[0] = array1; 
    Pos[1] = array2;
}

更多信息:


如果您想要/需要真正的Lists,您可以使用以下方法之一:

您正在寻找List<Integer[]>

static List<Integer[]> Pos = new ArrayList<Integer[]>();

static {
    Pos.add(new Integer[] { 0, 1 } );
    Pos.add(new Integer[] { 2, 3 } );
}

或者更好的选择:List&lt;List&lt;Integer&gt;&gt;:

static List<List<Integer>> Pos = new ArrayList<List<Integer>>();

static {
    List<Integer> list = new ArrayList<Integer>();
    list.add(0);
    list.add(1);
    Pos.add(list);
    list = new ArrayList<Integer>();
    list.add(2);
    list.add(3);
    Pos.add(list);
}

【讨论】:

  • 可能是一些小故障,或者你已经修复了。没关系。
【解决方案2】:

声明一个列表列表。

ArrayList<ArrayList<Integer>> pos = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
pos.add(list1);    
pos.add(list2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-22
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 2023-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多