Sunday, January 27, 2013

Multidimensional arrays, Java

You must have used multidimensional arrays in whichever programming languages you use. Here is a brief about different ways of declaring and accessing multi-dimensional arrays in java.

Say you want to represent the following data in 2-D array
0
1
A B C
D E F
G H I
J K L
M N O
P Q R S
T U V
W X Y Z

which in fact represent the keys on your phone.

You can declare such mapping as:

public static String[] mapping1[] =
{  {"0"},
    {"1"},
    {"A","B","C"},
    {"D","E","F"},
    {"G","H","I"},
    {"J","K","L"},
    {"M","N","O"},
    {"P","Q","R","S"},
    {"T","U","V"},
    {"W","X","Y","Z"}
};

public static String mapping2[][] =

{  {"0"},
    {"1"},
    {"A","B","C"},
    {"D","E","F"},
    {"G","H","I"},
    {"J","K","L"},
    {"M","N","O"},
    {"P","Q","R","S"},
    {"T","U","V"},
    {"W","X","Y","Z"}
};

public static String[][] mapping3 =

{  {"0"},
    {"1"},
    {"A","B","C"},
    {"D","E","F"},
    {"G","H","I"},
    {"J","K","L"},
    {"M","N","O"},
    {"P","Q","R","S"},
    {"T","U","V"},
    {"W","X","Y","Z"}
};

Note the difference in declaration but all these represent the same data (or same 2D array).
If you do:

System.out.println(Arrays.deepToString(mapping1));
System.out.println(Arrays.deepToString(mapping2));
System.out.println(Arrays.deepToString(mapping3));

then output will be same for all three wiz:
[[0], [1], [A, B, C], [D, E, F], [G, H, I], [J, K, L], [M, N, O], [P, Q, R, S], [T, U, V], [W, X, Y, Z]]

Also one more point worth noticing here is in order to access data there will be same accessor i.e.
if you want to access element 'B' (whose position in 2 D array is [2][1]) then accessor for three mappings will be same wiz
System.out.println(mapping1[2][1]);
System.out.println(mapping2[2][1]);
System.out.println(mapping3[2][1]);

Output: B

Source: http://stackoverflow.com/questions/1067073/java-multidimensional-array/1067087#1067087

No comments:

Post a Comment