英文:
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<ArrayList<Integer>>();
arrList.add(new ArrayList<Integer>(Arrays.asList(1, 2, 3)));
arrList.add(new ArrayList<Integer>(Arrays.asList(4, 5, 6)));
arrList.add(new ArrayList<Integer>(Arrays.asList(7, 8, 9)));
The data type of the parent ArrayList
is <ArrayList<Integer>>
. Each element in the parent arrList
is itself of type ArrayList
which contains Integer
s.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论