Peta Hillier
Peta Hillier

Reputation: 23

How can I make an array of my arrays in Java? (WITHOUT ArrayLists)

I have a few multidimensional arrays of type char[][]. Eg..

char[][] ARRAY_1 = {
    {'.','#'},
    {'$','@'}
}
char[][] ARRAY_2 = {
    {'.','#'},
    {'$','@'}
}

And I want to make an array or list of some sort such as

ARRAY = {ARRAY_1,ARRAY_2,...}

so I'll be able to put in ARRAY[1] (or something similar) and have it return the entire char[][] ARRAY_1

I am very new to programming with Java so I'm not sure what the best way to do this is.

Edit: I've just found out I'm not allowed to use ArrayLists.

Upvotes: 2

Views: 102

Answers (4)

Mikaal Anwar
Mikaal Anwar

Reputation: 1791

Try this:

List<char[][]> list = new ArrayList<>();
list.add(ARRAY_1);
list.add(ARRAY_2);

Or

char[][][] ARRAY = new char[length][][];
ARRAY[0] = ARRAY_1;
ARRAY[1] = ARRAY_2;

Or

char[][][] ARRAY = new char[][][]{ARRAY_1, ARRAY_2};

Further reading:

Upvotes: 1

Azhar Husain Raeisi
Azhar Husain Raeisi

Reputation: 197

You are using a Jagged Array...

Also try this

char[][] array = new char[5][];

array[0] = array1;
array[1] = array2;

Regards

Upvotes: 0

Stephen C
Stephen C

Reputation: 718778

So ... if you are not allowed to use lists ... this is one way to make an array of existing arrays.

 char[][][] ARRAY = new char[][][]{ARRAY_1, ARRAY_2};

Insight #1: an N-dimension array in Java is an array of N-1 dimension arrays (assuming N > 1).

Insight #2: arrays are indexed from zero.


How would I call the arrays individually again later on?

  1. You still have the names of the original arrays ... in your example.

  2. Base on insight #1":

    char[][] ARRAY_1_AGAIN = ARRAYS[0];
    System.out.println(ARRAY_1 == ARRAY_1_AGAIN);  // prints true
    

    Since ARRAY_1 is the first subarray of ARRAY (as per the previous example), we need to use ARRAYS[0] (not ARRAYS[0]) to access it.

Upvotes: 1

FileNotFoundEx
FileNotFoundEx

Reputation: 71

Direct answer: use ArrayList<char[][]> or char[][][].

Basically, you create an ArrayList that holds your 2 dimensional arrays or a 3 dimensional array of chars.

List<char[][]> array = new ArrayList<>();

or

char[][][] array = char[length][][];

To add the arrays, you just use the following:

array.add(arrayOne); //for an ArrayList
array.add(arrayTwo);

or

array[0] = arrayOne; //for an array
array[1] = arrayTwo;

To get the arrays, you just use the following (where the number is the index):

array.get(0); //for an ArrayList
array.get(1);

or

array[0]; //for an array
array[1];

Check out the ArrayList javadoc for more information.

(edit: variable changed to match naming conventions)

Upvotes: 4

Related Questions