如何使ArrayList在java中作为二维数组工作?

我想在java中使用arrayList对象作为二维数组。 我的问题是如何从arrayList中的特定维度访问值。

在二维数组中,如果我想访问值那么它可以是m [i] [j]。

但在arraylist我怎么能这样做?

你的意思是List中的List

可能是……

 List> twoDList = new ArrayList<>(); 

我想创建一个List,其中每个List键包含其中的另一个List

它应该更像你想要某种Map ,它基本上是一个键/值对。

 Map> mapValues = new HashMap<>(25); List listOfValues = ...; //... mapValues.put("A unique key for this list", listOfValues); //... List thatListOfValues = mapValues.get("A unique key for this list"); 
 List> list = new ArrayList>(); list.add(new ArrayList()); list.add(new ArrayList()); list.get(0).add(5); list.get(1).add(6); for(List listiter : list) { for(Integer integer : listiter) { System.out.println("" + integer); } } 

这样你就可以得到像这样的物品

 list.get(1).get(0); //second dimension list -> integer 

编辑:

虽然如果你试图为每个列表使用数字索引,你可以使用Map,如下所示:

 Map> map = new HashMap>(); map.put(0, new ArrayList()); map.put(5, new ArrayList()); map.get(0).add(new YourObject("Hello")); map.get(5).add(new YourObject("World")); for(Integer integer : map.keySet()) { for(YourObject yourObject : map.get(integer)) { yourObject.print(); //example method System.out.println(" "); } } 

虽然即使这样,列表的访问也会像以前一样,

 map.get(0).get(1); //List -> value at index 

显然,您不需要使用Integers作为generics类型参数,这只是一个占位符类型。

List>这样的解决方案很慢,那么你应该使用像一个维度数组

  // Two dimentions: m and n List arr = new ArrayList(m*n); for (int i=0; i< m; ++i) { for (int j=0; j 

记忆是这里的重要考虑因素。

使用1D容器对2D(或更高维度)arrays进行建模是可以接受的。 (这就是微软COM的VARIANT SAFEARRAY的工作方式。) 但是 ,如果元素的数量很大,请仔细考虑; 特别是如果容器分配连续的内存块。 使用像List这样的东西会模拟一个锯齿状的矩阵并且可以破坏你的记忆。

使用1D方法,您可以使用适当转换的ArrayList上的get(index)方法:

给定第(i)行和第(j)列,使用index = i * rows + j进行变换,其中rows是矩阵中的行数。

arraylist不是制作2维数组的对象。 但无论如何你都可以使用它:你可以使用:

 new ArrayList>; //or new ArrayList; 

但是你应该实现自己的矩阵类,因为你可能需要做一些检查,函数get(int row, int column)会很酷

另请考虑Google Guava库提供的Table集合。 ArrayTable是基于2D数组的实现。

你可以这样定义

1>

 List list = new ArrayList(); 

 list.get(i)[j]; 

2>

 List> list = new ArrayList>(); 

 list.get(i).get(j);