【发布时间】:2021-02-21 22:50:49
【问题描述】:
所以我一直在尝试创建一个 ArrayList of ArrayList of Generics。基本上我有一个名为 Color 的通用类(它在运行时接受 Integer/Long/short 值)。现在我想在一个名为 Picture 的类中创建一个“颜色”类型的二维数组列表。我有构造函数和arrayList 的声明。但我不明白的是为什么 ArrayList 的大小最终为 0,即使我声明大小大于 0。在代码之后更多关于此...
import java.util.ArrayList;
public class Picture{
private ArrayList<ArrayList<Color<?>>> pic;
//constructor that takes in height and width of 2d array, and a Color parameter that will be populated in the 2d list
public Picture(int height, int width, Color color){
if((height <= 0) || (width<=0)){
throw new IndexOutOfBoundsException("invalid height and/or width");
}
else{
pic = new ArrayList<ArrayList<Color<?>>>(height);
System.out.println("size of given array: "+ pic.size()); //for error handling purposes
for(int r =0; r< pic.size(); r++ ){
pic.set(r, new ArrayList<Color<?>>(width));
for(int c = 0; c< width; c++){
pic.get(r).set(c, color);
}
}
}
}
}
每次我通过创建一个新的图片对象(如 Picture pic1 =new Picture(3,4, new Color<Integer>(2)); 或任何大于 0 的值作为高度和宽度)来运行代码来测试它时;我总是最终得到“给定数组的大小:0”(来自System.out.println() 语句)并且for循环甚至没有发生,因为列表的大小最终为0。最后是整个颜色对象应该在 2d ArrayList 中发生的事情根本不会发生,“2d ArrayList - pic”最终什么都不包含。
我不明白我哪里出错了以及 2d ArrayList 被分配的大小为 0,即使我为它分配了“高度”一个保证大于零的值(因为 if陈述)。我假设我声明/初始化了 2d Arraylist - pic 错误。有人可以帮我吗?也请随时指出我的代码中的任何其他错误。
谢谢
【问题讨论】:
-
ArrayList<ArrayList<? extends Color>> pic;? -
所以我正在尝试创建一个 Color 的二维数组列表 - 这是一个泛型类。你说的是它是一个上限,我正在尝试创建一个 Color 子类的二维数组列表。我可以使 Picture 类通用并执行类似
ArrayList<ArrayList<Color<E>>> pic;的操作,但这会给我的其他类带来其他问题。除了Color<?>,还有其他方法吗?
标签: java generics arraylist multidimensional-array declaration