将列表添加到列表的空列表中

时间:2014-05-02 19:24:01

标签: java list

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

像:

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

"平面"应该回复:

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

这怎么可能?

2 个答案:

答案 0 :(得分:4)

从当前代码中,您需要初始化int s。

的数组数组
static int[][] Pos = new int[2][];

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

更多信息:


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

您正在寻找List<Integer[]>

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

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

或者更好的选择:List<List<Integer>>

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);
}

答案 1 :(得分: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);
相关问题