Java ArrayList阵列
我们经常遇到二维数组,其中数组中的大部分部分是空的。由于空间是一个巨大的问题,我们尝试不同的方法来减少空间。其中一个解决方案是,当我们知道数组中每一行的长度时,使用锯齿形数组,但当我们没有明确知道每一行的长度时,问题就来了。这里我们使用ArrayList,因为长度是未知的。
以下是一个Java程序来演示上述概念。
// Java code to demonstrate the concept of
// array of ArrayList
import java.util.*;
public class Arraylist {
public static void main(String[] args)
{
int n = 5;
// Here al is an array of arraylist having
// n number of rows.The number of columns on
// each row depends on the user.
// al[i].size() will give the size of the
// i'th row
ArrayList<Integer>[] al = new ArrayList[n];
// initializing
for (int i = 0; i < n; i++) {
al[i] = new ArrayList<Integer>();
}
// We can add any number of columns to each
// rows as per our wish
al[0].add(1);
al[0].add(2);
al[1].add(5);
al[2].add(10);
al[2].add(20);
al[2].add(30);
al[3].add(56);
al[4].add(34);
al[4].add(67);
al[4].add(89);
al[4].add(12);
for (int i = 0; i < n; i++) {
for (int j = 0; j < al[i].size(); j++) {
System.out.print(al[i].get(j) + " ");
}
System.out.println();
}
}
}
输出:
1 2
5
10 20 30
56
34 67 89 12
上述代码工作正常,但显示以下警告。
prog.java:15: warning: [unchecked] unchecked conversion
ArrayList[] al = new ArrayList[n];
^
required: ArrayList[]
found: ArrayList[]
1 warning
这个警告基本上是由于下面这句话引起的。
ArrayList<Integer>[] al = new ArrayList[n];
如何解决上述警告?
我们不能在没有警告的情况下使用ArrayList的数组。我们基本上需要使用ArrayList的ArrayList。
极客教程