3

Is it possible to create an array of 2D int arrays like:

int n = 100;
int[][] [] a = new int[][] [n];

Array has a fixed length n and matrices (2D arrays) have different non-zero sizes (at least 1 x 1).

For performance I would like to store that in the stack, not like:

ArrayList<int[][]> a = new ArrayList<int[][]>(n);

which will be stored on the heap as far as I know.

12
  • 4
    Arrays are always stored in the heap - at least notionally. They're reference types. (It's possible that very smart JVMs will perform escape analysis, but you should assume that it will be on the heap.) Commented Aug 15, 2012 at 18:31
  • Your arrays wouldn't be stored on the stack if they go into a collection. Java may try to optimize this (link; see Jon's note at the bottom of the answer) but it does not have to. Commented Aug 15, 2012 at 18:31
  • Suggestion, 2D array are overrated: Use a pseudo-2D-array with size of length * width, and access with [x+(length*y)] Commented Aug 15, 2012 at 18:32
  • Even some simple array like int[] a = new int[5] will be on the heap.. Alright, thanks for information, so ArrayList is a solution. Commented Aug 15, 2012 at 18:33
  • @ TheZ: very interesting, would be nice to see the reasons why [x*y] linear array is better than 2D array.. Commented Aug 15, 2012 at 18:34

2 Answers 2

4

To create a 3D array

int n = 100;
int[][][] a = new int[n][][];

This creates 100 array of array of any dimension.

This is almost as (in)efficient as

List<int[][]> a = new ArrayList<int[][]>(n);
Sign up to request clarification or add additional context in comments.

4 Comments

@downvoter Can you comment as to why?
+1 as consolation for the downvote (5:1 payback--win!).
Just for humor: nothing can be "almost as (in)efficient as X" since it would have to approach the efficiency of X from both sides at once :)
@MarkoTopolnik true, the difference doesn't matter either way. ;)
3

Is it possible to create an array of 2D int arrays like:

int n = 100;
int[][] [] a = new int[][] [n];

--> this is invalid with syntax, you will get compiler error. Use :

int n = 100;
int[][] [] a = new int[n][] [];

but a is an object as arrays in java are object so a will be stored on heap not on stack.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.