I’m trying to create a 2 dimensional array that is fairly large and I keep getting the error “java.lang.OutOfMemoryError: Java heap space”. I’ve tried the -Xmx command and I still get it.
Could there be an alternative I could use to 2D arrays? Or a way to increase heap size that works.
If not all elements of the matrix are occupied (or even share a very common default value), you can use a sparse matrix.
One of the simplest methods for doing this is using a HashMap:
You can iterate over all indices like this:
Iterating over only occupied indices is also easily possible:
Though this may return some cells that have been explicitly set to the default. What is more difficult with this implementation is iterating over only occupied indices in a specific order.
This is an example of a “dictionary of keys” implementation as described in the Wikipedia article linked above.