如何创建二维数组列表? [英] How to create a 2D ArrayList?
本文介绍了如何创建二维数组列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 Java 创建一个二维数组.行的大小是已知的,而列的大小是未知的.这是我的代码,但它不起作用.谁能给我一些想法?
I'm trying to use Java to create a 2-dimensional array. The size of rows is known, while the size of columns is unknown. Here is my code and it doesn't work. Could anyone give me some idea?
ArrayList<Integer> paths[];
paths = new ArrayList[2];// 2 paths
for (int i=0; i<2; ++i)
paths[i].add(1); // add an element to each path
推荐答案
在添加之前初始化数组元素.将初始化放入 for
循环中:
Initialize the array element before adding to it. Put the initialization into the for
loop:
@SuppressWarnings("unchecked")
ArrayList<Integer>[] paths = new ArrayList[2];
for (int i=0; i<2; ++i) {
paths[i] = new ArrayList<Integer>();
paths[i].add(1);
}
这样可以避免NullPointerException
.
这篇关于如何创建二维数组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文