我们可以在不定义列数的情况下定义 new Object[3][] 吗? [英] Can we define new Object[3][] without defining number of columns?
问题描述
有人可以帮我理解下面的代码吗?我是 Java 新手,我正在尝试学习 Objects[].此代码编译但 retval 不返回任何内容?
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?
我在网上做了很多搜索,但找不到为什么 Object[3][] 编译并且不抱怨?
I've done a lot of search online but can't find why is Object[3][] compiles and does not complain?
下面的代码是什么意思?
(新对象[1])[0] = tt;
What does the following code mean?
(new Object[1])[0] = tt;
如何才能retval[0] = new Object[1];"如果 Object 是二维数组则编译.
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;
}
}
推荐答案
请记住,创建一个二维数组只是创建一个数组数组.二维数组中数组的长度与保存它们的数组无关.
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;
在这个例子中,我们创建了一个可以容纳 3 个数组的二维数组 'r'.然后我们定义一个可以容纳 2 个对象的一维数组 'j'.然后我们将'r'的第一个数组设置为'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.
这篇关于我们可以在不定义列数的情况下定义 new Object[3][] 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!