Xah Lee, ,
A n-dimensional array in java needs not be rectangular. For example, normally a 2D array can be thought of as a matrix of m rows and n columns; any row has same number of slots as any other row. However, in Java you could create a 2D array with m rows and each row have different number of slots.
Here is a example.
public class Ar3 { public static void main(String[] args) { int[][] myA = { { 3, 4, 5 }, { 77, 50 }}; // special syntaxt to create jagged array in one shot. for (int i = 0; i < myA.length; i++) { for (int j = 0; j < myA[i].length; j++) { System.out.print(myA[i][j] + " "); } System.out.println(); } } }
Normally, array creation takes 3 steps in java:
int[] myAmyA = new int[10];myA[0]=3; myA[1]=5;There's a irregular syntax that does all the above steps in one, like this: int[][] myA = { { 3, 4, 5 }, { 77, 50 }};.
Note: even though the leafs of a array can be jagged, but not any middle level nodes. So, arbitrary tree cannot be created as array. For example, you cannot create a array with a shape like this: “{ { 3, 4, 5 }, { 77, 50, {1, 2} }}”
You can make a array of Objects in Java. Here is a example.
class H { int x; H (int n) {x=n;} } public class Ar4 { public static void main(String[] args) { H[] myA; myA = new H[4]; for (int i = 0; i < myA.length; i++) { myA[i] = new H(i); System.out.print(new Integer(myA[i].x) +" "); } } }
Note the line H[] myA;. It declares that the variable myA is a datatype of array of H. The line myA = new H[4]; assigns this variable myA a thing, and that thing is a array of 4 elements, and each element is of type H.
The line myA[i] = new H(i);
sets the value for each slot of myA. And, that value being the
instantiation of H with i as the init parameter to the constructor of H.
In this irregular but convenient syntax: int[] v = {3,4};, it does several things in one shot: {array type declaration, value assignment, number of elements declaration, slots fulfillment}. However, this syntactical idiosyncracy cannot be used generally. For example, the following is a syntax error:
int[] v = new int[2];
v = {3, 4};
Here's a complete code you can try.
public class H { public static void main(String[] args) { int[] v = new int[2]; v = {3,4}; System.out.print(v[0]); } }
The compiler error is: “illegal start of expression”.
blog comments powered by Disqus