I would like to represent matrix-like data in a suitable data-structure in Java. The dimensions of this matrix depend on user-input. One way would probably be to use a “magic” max-constant, and use a simple multidimensional array. But operations on the data depend heavily on the dimension, and I would like to avoid fixed arrays, since I’d always need to keep track of the used vs. maximal dimension. A more dynamic approach of course is to define something like
private ArrayList<ArrayList<ArrayList<Point>>> arr3d = new ArrayList<ArrayList<ArrayList<Element>>>();
I think this is unacceptably ugly. It might be better to define a custom data-structure, i.e. a one-dimensional ArrayList (or Vector), and then somehow wrap this i.e. map an access specified as [i,j,k] to some element of that single list. Is it possible to overwrite the operator []? How to do this efficiently? Is there some existing library or code I could lean on?
PS: I thought this might be a common problem, but despite best efforts I have not found an existing question. Apologies in advance if I missed some answer.
Why don’t you create your own class to wrap that? It could contain your 3d list internally, but you expose only “user-friendly” methods to access and set elements.
And no, in Java it’s not possible to overload []
A quick helper for that:
You can even do it in one line if you’re not worried about readability:
And you need put methods, that creates the rows (as ArrayList) when needed.