3

这是我的情况,我想为我正在处理的 3d 项目创建一个矩阵缓冲区。

Stack Overflow 上的很多人都在提议做这样的事情

ArrayList<ArrayList<object>>

但是,这种结构会引起问题,因为我需要一个固定大小的矩阵,并且我知道它对add(i,object)操作复杂性的影响。另一方面,我的矩阵的最后一个嵌套级别需要具有可变大小,因此如果对象位于同一位置,它只会将其自身添加到堆栈中。

4

2 回答 2

2

If you need a matrix with a variable length 3rd dimension, why not do ArrayList[][]?

Obviously you can't instantiate a generic matrix, but you can cast it from the raw-type to Object (assuming that's what you want) like this:

ArrayList<Object>[][] box = (ArrayList<Object>[][])new ArrayList[length][width];

This would result in a fixed size matrix with a variable length 3rd dimension. Remember to fill the matrix with ArrayList's though, as the whole matrix will be filled with null to begin with.

于 2013-06-22T03:47:13.033 回答
1

可变长度的第三维可以由许多不同的集合处理。如果您的第 3 维真的像堆栈(甚至是队列/双端队列),那么我会使用LinkedList它来处理它,因为它可以从集合的前/后添加和删除对象的速度。

为了创建类型列表的二维矩阵,E您可以编写:

LinkedList<E>[][] matrix = new LinkedList[length][width];

然后在那之后,我建议像这样实例化所有列表,以防止出现空指针问题:

for(int i = 0; i < matrix.length; i++)
    for(int j = 0; j < matrix[0].length; j++)
        matrix[i][j] = new LinkedList<>();

我确实假设您使用的是 Java 7。如果没有,只需E在实例化每个元素时将类型 ( ) 放入尖括号中。我希望这会有所帮助,并且玩得开心!=)

于 2013-06-22T04:05:44.700 回答