如何创建一个2D的ArrayList? [英] How to create a 2D ArrayList?

查看:139
本文介绍了如何创建一个2D的ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Java创建一个2维数组。行的大小是已知的,而列的大小是未知的。这里是我的code和它不工作。任何人都可以给我一些想法?

 的ArrayList<整数GT;路径[];
路径=新的ArrayList [2]; // 2路
对(INT I = 0; I&2 ++ⅰ)
    路径[Ⅰ]。新增(1); //元素添加到每个路径


解决方案

增加它之前,初始化数组元素。把初始化到循环:

  @燮pressWarnings(未登记)
ArrayList的<整数GT; [] =路径的ArrayList新[2];对(INT I = 0; I&2 ++ⅰ){
    路径[我] =新的ArrayList<整数GT;();
    路径[Ⅰ]。新增(1);
}

这样就可以避免 NullPointerException异常

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

解决方案

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);
}

This way you can avoid the NullPointerException.

这篇关于如何创建一个2D的ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆