如何在Java中编写二维ArrayList?

huangapple go评论70阅读模式
英文:

How to write 2d arraylists in java?

问题

我知道如何编写“arraylists”,但不太清楚如何编写“2d arraylists”。你们能帮我吗?

英文:

I know how to write arraylists, but don't quite know how to write 2d arraylists. Can you guys help me?

答案1

得分: 1

SomeObject[] 是数组,SomeObject[][] 是二维数组。下面是一个整数二维数组的示例。

int[][] array2d = new int[][] {
  {1,2,3},
  {4,5,6},
  {7,8,9}
};

array2d[1][1] == 5; // 这是真的

没有二维 ArrayList,你可以通过创建普通的 ArrayList 数组或包含多个 ArrayList 的 ArrayList 来“模拟”它。

// ArrayList 数组
ArrayList[] arr = new ArrayList[arraysize];

// 包含另一个 ArrayList 的 ArrayList
ArrayList a = new ArrayList();
ArrayList b = new ArrayList();
a.add(b);
英文:

SomeObject[] is array and SomeObject[][] is 2D array. Below you can see example integer 2D array.

int[][] array2d = new int[][] {
  {1,2,3},
  {4,5,6},
  {7,8,9}
};

array2d[1][1] == 5; // this is true

There are no 2D ArrayLists, you can fake it by making normal array of ArrayLists or ArrayList containing multiple ArrayLists.

// Array of ArrayLists
ArrayList[] arr = new ArrayList[arraysize];

// ArrayList containing another ArrayList
ArrayList a = new ArrayList();
ArrayList b = new ArrayList();
a.add(b);

</details>



# 答案2
**得分**: 1

2D数组在Java中实质上是由数组组成的数组。数组中的每个元素本身都是一个数组。

```java
int[][] arr = {
    { 1, 2, 3 },
    { 4, 5, 6 },
    { 7, 8, 9 }
}

使用ArrayList也可以创建相同的结构。

ArrayList<ArrayList<Integer>> arrList = new ArrayList<>();
arrList.add(new ArrayList<>(Arrays.asList(1, 2, 3)));
arrList.add(new ArrayList<>(Arrays.asList(4, 5, 6)));
arrList.add(new ArrayList<>(Arrays.asList(7, 8, 9)));

父级ArrayList的数据类型是ArrayList<Integer>。父级arrList中的每个元素本身都是ArrayList类型,其中包含Integer

英文:

2D arrays in Java are essentially arrays consisting of arrays. Each element in the array is itself an array.

int[][] arr = {
    new int[] = { 1, 2, 3 },
    new int[] = { 4, 5, 6 },
    new int[] = { 7, 8, 9 }
}

The same can be created with ArrayLists.

ArrayList arrList = new ArrayList&lt;ArrayList&lt;Integer&gt;&gt;();
arrList.add(new ArrayList&lt;Integer&gt;(Arrays.asList(1, 2, 3)));
arrList.add(new ArrayList&lt;Integer&gt;(Arrays.asList(4, 5, 6)));
arrList.add(new ArrayList&lt;Integer&gt;(Arrays.asList(7, 8, 9)));

The data type of the parent ArrayList is &lt;ArrayList&lt;Integer&gt;&gt;. Each element in the parent arrList is itself of type ArrayList which contains Integers.

huangapple
  • 本文由 发表于 2020年4月6日 08:50:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/61051439.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定