2015-01-21 63 views
-2
//I want my to be something like this: [[0,0],[0,1],[0,2].....,[4,2],[4,3]] 


public class Japan { 

public static void main(String[]args) { 
    ArrayList<ArrayList<Integer>> nodes = new ArrayList<ArrayList<Integer>>(); 
    ArrayList<Integer> nodeList = new ArrayList<Integer>(); 
    for(int i =0;i<5;i++) { 
     for(int j=0;j<4;j++) { 
      nodeList.add(i); 
      nodeList.add(j); 
      nodes.add(nodeList); 
      nodeList.remove(1); 
      nodeList.remove(0); 
     } 
    } 
    System.out.println(nodes); 
}} 
+1

看起来你需要输入一些代码... – Dima 2015-01-21 02:47:57

回答

0

你的问题是因为您正在重新使用相同的内部ArrayList - 您将内部ArrayList添加到外部ArrayList几次,并且添加到内部ArrayList的所有内容都将被删除,因此当您打印它时,内部li st是空的。

nodes.add(nodeList)确实不是复制nodeList - 它增加了对同一个列表的引用。

你需要,当你调用nodes.add要么创建一个副本:

public class Japan { 

public static void main(String[]args) { 
    ArrayList<ArrayList<Integer>> nodes = new ArrayList<ArrayList<Integer>>(); 
    ArrayList<Integer> nodeList = new ArrayList<Integer>(); 
    for(int i =0;i<5;i++) { 
     for(int j=0;j<4;j++) { 
      nodeList.add(i); 
      nodeList.add(j); 
      nodes.add(new ArrayList<>(nodeList)); // This copies nodeList, and adds the copy to nodes 
      nodeList.remove(1); 
      nodeList.remove(0); 
     } 
    } 
    System.out.println(nodes); 
}} 

或通过循环创建一个新的内部列表中的每个时间:

public class Japan { 

public static void main(String[]args) { 
    ArrayList<ArrayList<Integer>> nodes = new ArrayList<ArrayList<Integer>>(); 
    for(int i =0;i<5;i++) { 
     for(int j=0;j<4;j++) { 
      ArrayList<Integer> nodeList = new ArrayList<Integer>(); // this creates a new list each time it is executed 
      nodeList.add(i); 
      nodeList.add(j); 
      nodes.add(nodeList); 
     } 
    } 
    System.out.println(nodes); 
}} 

这两项工作,但我(可能大多数程序员)发现第二个更容易理解,所以我更喜欢这种方法。 (如果你不能看到为什么第二个是更容易理解,它会来找你的时候)

+0

感谢帮帮我 – 2015-01-21 09:02:47

0

你需要确保你对每个i指标的初始化列表,

for(int i = 0; i < 5; i++){ 
    list.add(new ArrayList<Object>()); 
} 

然后执行以下操作:

for(int i = 0; i <5; i++){ 
    for(int j = 0; j < 4; j++){ 
     list.get(i).add(j); 
    } 
} 
+0

感谢您的时间迈克 – 2015-01-21 09:04:09