Thomas McAdams wrote:Yeah I am still new to arrays. From the looks of it by the reference I better start over. Thank you all for the input though! I am starting to understand it now.
From the looks of it, you were thinking along the right lines; it's just your final result was a bit off. "2D" arrays (ie,
<whatever>[][]) are usually used to contain "grids" of information, such as:
private Square[][] chessBoard = new Square[8][8];
or:
private int[][] matrix = new int[4][6]; // a matrix of 4 rows by 6 columns
However, "2D" is a bit of a misnomer. In
Java, ALL arrays are
one-dimensional;
but each element of an array can itself be an array.
Thus, a
String[][] is NOT a grid of Strings (as it
is in some languages), it is an
array of
String[]s - each of which is an array of
Strings.
And this isn't just "mechanical fluff"; it actually makes 'multi-dimensional' arrays much more flexible.
For example: suppose I wanted to read in the first hundred lines of a text file into my program and store it as a table of characters. I don't know what each line looks like, but I do know that the longest they can be is 100 characters.
If I was forced to create a
two-dimensional array, it would have to look something like:
private char[][] textCharacters = new char[100][100]; (100 lines of 100 characters each)
ie, 10,000 characters.
Always. But in Java I can create a:
private char[][] textCharacters = new char[100][]; (100 lines of unknown length)
and then read my file into it with:
and now
textCharacters will only take up as much space as the lines I read in.
Furthermore, if I read in a line that's
longer than 100 characters, it will still work.
From the look of it, you probably already knew some of this, but I thought a concrete example might help.
Winston