0

For instance, I have a 2-D array:

1 2 3 4 5

6 7 8 9 10

11 12

It's an 3 by 5 array. However, in the third row, I only need to fill two cells. The remaining ones are unnecessary, but it's created when initializing the array.

The reason I want to so this is that my actual array's row is very long, so that potentially wastes a big chunk of memory, because i only need to use two cells in the 3rd row.

Is there a way to shorten the third row to contain two cells only after the array is filled up?

I am not sure it's possible, or it's the best way to do it. Thank you.

user697911
  • 10,043
  • 25
  • 95
  • 169
  • 3
    Java arrays can be jagged. – ChiefTwoPencils Jun 28 '14 at 21:29
  • You could use an array with linked-lists attached but unless there is a huge difference in length I don't think this would be worth it. Maintaining a linked list would add a lot more additional overhead as well making it harder to find a value in your list. – Ellery Jun 28 '14 at 21:30
  • You can always write your own implementation of 2D array. – kukis Jun 28 '14 at 21:32
  • 2
    Rather than declaring a `new Thing[X][Y]`, declare a `new Thing[X]` and then loop and set the arrays to the correct size. – Boris the Spider Jun 28 '14 at 21:32
  • possible duplicate of [Sparse matrices / arrays in Java](http://stackoverflow.com/questions/390181/sparse-matrices-arrays-in-java) – Patricia Shanahan Jun 28 '14 at 21:35
  • Could you be more specific on "declare a new Thing[X] and then loop and set the arrays to the correct size"? Thanks. – user697911 Jun 28 '14 at 21:35

1 Answers1

4

You can't shrink arrays in java because you can't change their length, however you can set the inner arrays of a 2-D array to arrays of different lengths.

int[][] ar = new int[3][];
ar[0] = new int[]{1, 2, 3, 4, 5};
ar[1] = new int[]{6, 7, 8, 9, 10};
ar[2] = new int[]{11, 12};
Alex - GlassEditor.com
  • 14,957
  • 5
  • 49
  • 49