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.
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!
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.
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.
Related
Well, that might be a strange question, and maybe just because I'm not familiar enough with Java.
So, I declared a 2D int array:
int[][] arr = new int[0][10]
Now, as you can see, the second dimension's length is 10, while the first dimension's length is 0. I'm not sure how Java treats these kind of arrays, but the compiler doesn't produce any errors, which means it's a legit declaration.
Well, I passed the array to some function, and I want to retrieve from within the function, the length of the second dimension.
Of course something like:
arr[0].length
won't work. is there another way to do this?
The objects created by new int[0][10] and new int[0][20] are equivalent. There is no logical "second dimension" here. Effectively you're running something like this:
int[][] createArray(int d1, int d2) {
int[][] ret = new int[d1][];
for (int i = 0; i < d1; i++) {
ret[i] = new int[d2];
}
return ret;
}
Now if you translate that into your scenario, you'll end up with code which never reads d2.
If you want to represent a general-purpose rectangular array (instead of an array of arrays) you might want to consider creating your own type for it.
Arrays in Java, and most every other programming language, are zero-based. Consider this 2D array:
int[][] arr = new int[1][10];
This means that there is one row and ten columns in it.
Now, consider this array:
int[][] arr = new int[0][10];
This means that there are zero rows and (an irrelevant amount of columns) in it.
If you try to index into the second array, you'll find that you can't - an array of length zero has no starting point.
The compiler sees it as valid because you declared dimensions with it, but you won't be able to actually use it in any meaningful way in Java.
There is no such thing as the length of the second dimension. Consider:
int[][] arr = new int[10][10];
arr[5] = new int[42];
What is the length of the second dimension? 10 or 42?
No. It doesnt work this way. arr is an array with ten elements, each of which must be a reference of an int array (or null). That's all there is to say.
When I was taught 2d arrays, I was taught that they are arrays of arrays, similar to an array of ArrayLists. But I was thinking about it and it is actually really confusing:
ArrayList[] arrOfList = new ArrayList[5];
arrOfList[0] = new ArrayList<Integer>();
arrOfList[0].add(1);
arrOfList[0].add(2);
arrOfList[0].add(3);
//arrOfList[0] is the first list, with 3 elements
//arrOfList is an array of 5 lists; arrOfList.length = 5
int[][] arrOfArr = new int[3][5];
//arrOfArr[0] is NOT an array with 3 elements
//arrOfArr is NOT an array of 5 arrays; arrOfArr.length = 3
I think what I'm getting at is more clear if I bold the parts that I think would correlate (but don't):
ArrayList[] arrOfList = new ArrayList[5];
int[][] arrOfArr = new int[3][5];
What is a more intuitive way of thinking about declaring 2d arrays, since relating it to an arbitrary type is not right? (as illustrated above)
This may help you visualize it more.
When using square brackets [], first pair is always row, second pair is columns.
In both scenarios, the first dimension (row) saves the memory address of the corresponding Array / ArrayLists.
The second dimension (column) saves the corresponding value stored in that particular row of Array/ArrayList.
What you are taught is correct. An array of arrays is similar to an array of arraylists, with the exception that arraylists have variable length. The implication is that with an array of arraylists, the width (no. of columns) isn't static.
ArrayList[] arrOfList = new ArrayList[5]
This is saying, create an Array of length 5 (5 rows), with the data type being ArrayList (of variable length, thus can be any number of columns).
int[][] arrOfArr = new int[3][5]
This is saying, create an Array of length 3 (3 rows), with the data type being Array with length 5 (5 columns).
The fact that an ArrayList has variable length is likely causing the confusion, but I still stand by the same answer: first pair of [] = row; second pair of [] = column.
int[][] arrOfArr = new int[3][5]
That creates an empty grid of array cells with 3 rows and 5 columns. i.e.
[][][][][]
[][][][][]
[][][][][]
Then to fill those columns you just do arrOfArr[0][2] = 4 which goes down to row 0 and across to column 2. i.e.
[][][4][][]
[][][][][]
[][][][][]
Alternatively, see it as a set of 3 lots of 5 cell arrays
[][][4][][], [][][][][], [][][][][]
int[][] arrOfArr = new int[3][5];
//arrOfArr[3] is the number of rows
//arrOfArr[5] is the number of colums
Im using
ArrayList<ArrayList<String>> Stringdata = new ArrayList<ArrayList<String>>();
to make a 2d array of string
how is it different from using
String Stringdata[][] = new String[10][10];
An ArrayList is a class that implements the interface List.
An array as per declared by:String[] variable is a finite-length data-structure in Java.
The main difference in using a 2D ArrayList instead of a normal array is that the length of an ArrayList is not limited. You may add as many elements to an ArrayList as your RAM allows.
On the other hand, String[][] stringData = new String[10][10]; would limit this matrix to 100 elements (10 rows with 10 elements each). If trying to add an element to index 10 (notice the index only goes from 0 to 9) of a 10x10 matrix, the compiler would throw an error.
In general, if you already know how many spaces you will need in your matrix it is recommended that you use an array. Else, ArrayLists are really good.
Background
This is a 2d array.-
String[][] names = { {"Sam", "Smith"}, {"Robert", "Delgro"}, {"James", "Gosling"}, };
I can access the rows by calling this:
names[n]
Where n is any integer between the bounds and in this case 0<=n<=names.length-1.
Likewise
I can call this
String [] rowOne = names[0];
Inquiry
The question now remains,instead of rows, is there a way to access a specific column in the same way a specific row is accessed.
Feedback
I would like feedback on this suggestion.
In the particular case of accessing a column in a 2d array,names[][x]would be the declaration to call a specific column,where 0<=x<=names[0].length-1.
String[] columnOne = names[][0]
This would mean that names.length would be equivalent to calling names[][x].length
This could also work for arrays greater than a 2d array.
String[][][]names = { {{"Sam", "Smith"}, {"Robert", "Delgro"}}, {{"James", "Gosling"}}};
Just add extra square brackets.
For example In a 3d array, to access an aisle, which is what I will refer to the 3rd dimension.
names[][][z], where 0<=z<= names[0][1].length-1
One dimensional arrays from multi-dimensional arrays.
...is there a way to access a specific column in the same way a specific row is accessed.
No; Java's multidimensional arrays are essentially arrays that contain references to other arrays are not contiguous in memory. Java also allows arrays to be jagged. Let's say you have the following multidimensional array:
int[][] array = {
{1, 2, 3},
{4, 5},
{6}
};
By calling array[][2], what would you expect to receive? What about array[][3]?
To be able to get an array of columns, you would need to first transpose the multidimensional array.
public static int[][] add2DArrays(int[][]A, int[][]B) {
return int[][] C;
}
I understand how to populate this new array by adding the sums of the two arrays A & B, the road block I am facing is creating this initial array C. We cannot assume the size of the arrays given as parameters, so that is the part I am having a problem with.
I know by doing:
int[][] C = new int[A.length+B.length][]; //this will only give me the # of rows;
I am stuck on how to get the proper length of columns for the rows in the new array. I am thinking it may be possible to some how record the length of the longest row in A, and then record the longest row in B, and choose the bigger of the two, but that seems messy and inefficient. Thank you all for your support.
If both are really 2D arrays -- that is, the length of all the rows is the same -- and row 0 was actually allocated, you can get the summed length of a row from A[0].length+B[0].length
If the length of the rows might vary -- which is perfectly legal in Java -- then you might need to iterate through A and B to find the longest row and use that length.