BubbleTree
BubbleTree

Reputation: 606

Element of an array as a reference to another array?

I am trying to have a 2D Array that is 16 rows by 11 columns where row 0, column 3 is a reference to another array that is a single dimension array. How do i go about doing this? I already have both arrays where the single dimension array is a char array(although i could make it a string array if i wanted) and the 2D array is a string array. The rest of the 2D Array is filled with plain strings for each elements with the exception of row 0, column 3 which i want it to be the single dimension array.

Upvotes: 0

Views: 134

Answers (3)

Alex Coleman
Alex Coleman

Reputation: 7326

Object[] arrayToReference = ...;
Object[][] arrayWithReference =  new Object[] { ..., arrayToReference, ...};

This should work; just reference the array and it should change as the original changes

Here's an example code snippet:

    Object[] array = new Object[] { "Test!" };
    Object[][] arrayArray = new Object[][] { array };
    System.out.println("Before: " + arrayArray[0][0]);
    array[0] = "Test2!";
    System.out.println("After: " + arrayArray[0][0]);

which has the following output:

Before: Test!
After: Test2!

Upvotes: 2

Aleksandar Stojadinovic
Aleksandar Stojadinovic

Reputation: 5049

I'm thinking a bit of an overkill solution, but should work for this with some refining. If it is possible for you.

Can you make two classes that implement the same interface? First one will be the type of the 2D array, and the other one would be class with the 1D array.

Since they implement a common interface, you can make a 2D array with that interface. That kind of 2D array can accept any kind of the two objects on any place in it.

Upvotes: 0

Simon Germain
Simon Germain

Reputation: 6844

That just sounds like your approach to the problem is wrong. Maybe you should rethink your data structure. Normally, an array is typed. You can't really decide to insert a different type in one cell.

If you really can't change the data structure, try inserting a single dimension array of strings in each cell with only 1 entry in them, which is the string that goes there normally, except for row 0, column 3, which already is an array.

Upvotes: 0

Related Questions