问题
Can someone please help me understand the following code? I'm new to java, I'm trying to learn Objects[]. This code compiles but retval does not return anything?
I've done a lot of search online but can't find why is Object[3][] compiles and does not complain?
What does the following code mean?
(new Object[1])[0] = tt;How can "retval[0] = new Object[1];" compile if Object is two dimensional array.
package Package1; import org.testng.annotations.Test; public class Test1 { @Test public void NewTest() { Object[][] retval = new Object[3][]; int i = 0; String methodName = "NewTest"; String className = this.getClass().toString(); String desc = "This is a test"; TestTest tt = new TestTest(methodName, className, desc); System.out.println(tt.str1); System.out.println(tt.str2); System.out.println(tt.str3); (new Object[1])[0] = tt; retval[0] = new Object[1]; retval[1] = new Object[1]; retval[2] = new Object[1]; System.out.println("object 0 = " + retval[0]); System.out.println("object 1 = " + retval[1]); System.out.println("object 2 = " + retval[2]); }
}
package Package1; public class TestTest { String str1 = "apple"; String str2 = "grape"; String str3 = "orange"; public TestTest(String a, String b, String c) { this.str1 = a; this.str2 = b; this.str3 = c; }
}
回答1:
Remember that creating a 2D array is just making an array of arrays. The length of the arrays within the 2D array is no concern of the array holding them.
Object[][] r = new Object[3][]; Object[] j = new Object[2]; r[0] = j;
In this example, we create a 2D array 'r' that can hold 3 arrays. Then we define a 1D array 'j' that can hold 2 Objects. Then we set the first array of 'r' to be 'j'.
However, if you want the length of the arrays within your 2D array to be a specific value; you will have to assign it a value.
Remember that referring to an index in an array is the same no matter the dimension of the array. What the array contains will be different however.
来源:https://stackoverflow.com/questions/65117157/can-we-define-new-object3-without-defining-number-of-columns