如何在Java中对ArrayList的ArrayList进行操作?

时间:2013-10-01 15:02:27

标签: java arraylist

在Java中运行ArrayList的ArrayList时遇到问题。我的代码中有这个东西 -

ArrayList<ArrayList<Integer>> L1 = new ArrayList<ArrayList<Integer>>();

问题是,我不知道我应该如何对此进行操作(添加,删除,遍历等)。我希望创建一个邻接列表(用于实现简单的无向图),我的教师建议我应该创建一个ArrayList的ArrayList。我知道我可以执行以下操作来添加新元素 -

L1.add(//Something I want to add);

但是由于显而易见的原因,这会在当前案例中引发错误。

6 个答案:

答案 0 :(得分:2)

ArrayList的{​​{1}},只要认为外部对象是ArrayList就可以了。

ArrayList

顺便说一句,邻接列表只是一个边列表,没有必要为每个顶点存储它们,特别是如果图形是无向的。 ArrayList<ArrayList<Integer>> list2d = new ArrayList<ArrayList<Integer>>(); // add an element to the list list2d.add(new ArrayList<Integer>()); // retrieve a list ArrayList<Integer> list1d = list2d.get(0); // add an integer list2d.get(0).add(123); 列表就足够了:

Edge

如果你想在每个顶点的基础上存储它们,那么你可以通过将边缘封装在顶点类本身内来避免使用列表列表,但这将需要两倍的边缘:

class Edge {
  Vertex v1, v2;
}

ArrayList<Edge> adjacencyList;

但哪一个最好取决于您需要在图表上执行的操作类型。对于小图表,没有实际差异。

另一种可能的实现,如果您只需要知道两个顶点是否已连接:

class Vertex {
  int value;
  ArrayList<Vertex> adjacency;
}

答案 1 :(得分:1)

尝试L1.get(i).add(whatever);,当然首先检查L1.get(i)是否存在,否则先添加内部列表。

这是这样的:

List<List<Integer>> L1 = new ArrayList<List<Integer>>(); //better use interfaces

List<Integer> first = null;
if( L1.size() > 0) {
 first = L1.get(0); //first element
}
else {
  first = new ArrayList<Integer>();
  L1.add(first);      
}

first.add(4711); //or whatever you like to add

答案 2 :(得分:1)

L1.add(new ArrayList<Integer>());

将在第一个列表中创建一个新列表。那你可以

L1.get(0).add(5)

答案 3 :(得分:1)

List<List<Integer>> L1 = new ArrayList<ArrayList<Integer>>();    
List<Integer> list1 = new ArrayList<Integer>();     
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);
list1.add(5);

//将列表添加到列表

L1.add(list1); 

遍历列表列表

for( List<Integer> list: L1 ){
      for(Integer i:list){
          System.out.println(i);
      }
}

答案 4 :(得分:1)

您只能将ArrayList类型的对象添加到L1。所以你可以这样做:

ArrayList<ArrayList<Integer>> firstList = new ArrayList<ArrayList<Integer>>();

ArrayList<Integer> secondList = new ArrayList<Integer>();
secondList.add(0);

firstList.add(secondList);

答案 5 :(得分:1)

要向外部数组添加新元素:

ArrayList<Integer> inner = new ArrayList<Integer>();
L1.add(inner);

然后将元素添加到内部数组:

   int exampleInt = 10;
   ArrayList<Integer> inner = L1.get(0);
   inner.add(exampleInt);

遍历所有数组中的所有元素:

   for (ArrayList<Integer> inner : L1)
   {
      for (Integer element : inner)
      {
         System.out.println(element);
      }
   }