Reputation: 1276
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.
Upvotes: 2
Views: 3092
Reputation: 81154
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:
Map<Point, Integer> matrix = new HashMap<Point, Integer>();
matrix.put(new Point(5, 2), 7);
Integer fiveTwo = matrix.get(new Point(5, 2));
You can iterate over all indices like this:
for ( int i = 0; i < ROW_COUNT; i++ ) {
for ( int j = 0; j < COL_COUNT; j++ ) {
Integer val = matrix.get(new Point(i, j));
//val is null here if not stored in the matrix. Replace with a different
//default as desired. eg:
//if ( val == null ) val = 0;
process(val);
}
}
Iterating over only occupied indices is also easily possible:
for ( Entry<Point, Integer> entry : matrix ) {
process(entry.getValue());
}
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.
Upvotes: 4
Reputation: 19737
Consider using the Flyweight pattern to make allocation of your objects less expensive. As Jon Skeet (Tips hat) is getting at, it really depends on how big the array is, and what's in it. Flyweight can buy you a lot sometimes, but only so much.
Upvotes: 1