3

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.

0

2 Answers 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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok casting sounds like a possible solution. I am doing something similar currently but I am not casting. I feel there should be a better solution no? Isnt there any colletion object with a similar structure than a array ?
The Collections that are similar to arrays (that is, lists) are LinkedList, ArrayList, and Vector. ArrayList is preferable to Vector, and generally ArrayList has much faster access than LinkedList, and uses much less memory, so it's usually what you want. If you have more specific constraints to this third dimension, such as only adding at the front or back, you could use an ArrayDeque, or a Stack, aside from that you really use ArrayList.
1

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! =)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.