Mark Odey
Mark Odey

Reputation: 305

How to program a 3-dimensional Matrix using ArrayList and Array

Here is my case, I would like to create a matrix buffer for a 3d project I am working on.

Many people on Stack Overflow are proposing doing something like this

ArrayList<ArrayList<object>>

However this structures is causing issues as I need a fixed sized matrix and I am aware of the impact that add(i,object) as on the complexity of the operation. On the other hand my last nested level of my matrix needs to be of a variable size so if the object is at the same position it just adds it self to the stack.

Upvotes: 3

Views: 557

Answers (2)

Erik Nguyen
Erik Nguyen

Reputation: 869

The variable length 3rd dimension can be handled by many different collections. If your 3rd dimension truly acts like a Stack (or even a Queue/Deque) then I would use LinkedList to take care of it due to the speed with which it can add and remove objects from the front/back of the collection.

In order to create the 2D matrix of lists of type E you could write:

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

Then right after that, I would suggest instantiating all of the lists like so in order to prevent null pointer problems:

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

I did assume that you were using Java 7. If not, simply put the type (E) into the angle brackets when instantiating each element. I hope this helps, and have fun coding! =)

Upvotes: 1

Robert Mitchell
Robert Mitchell

Reputation: 892

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.

Upvotes: 2

Related Questions