简体   繁体   English

关于创建类数组的困惑

[英]confusion about creating a class array

Suppose I have two classes in a Java Package: 假设我在Java包中有两个类:

Class1.java and Class2.java Class1.javaClass2.java

So, if in Class1.java , I do the following: 因此,如果在Class1.java ,我将执行以下操作:

public Class2[] QR;

public static int x = 10;

Then later on somewhere in the code: 然后在代码中的某个地方:

QR = new Class2[x];

So basically, I will be passing value 10 to class2 , right? 所以基本上,我将把值10传递给class2,对吧? Please correct me if I have not understood it properly. 如果我不正确地理解它,请纠正我。

QR = new Class2[x];

这将创建一个大小为10的Class2数组。

No you are not passing 10 to the value of class2. 不,您没有将class2的值传递10。 You are making an array of class2 whose size is 10. 您正在创建一个大小为10的class2数组。

Detail explaination: 详细说明:

public Class2[] QR;

In this statement you are saying, Hey i want to hold some objects of Class2 in an array whose name is QR. 在此声明中,您说的是,嘿,我想将Class2的某些对象保存在名称为QR的数组中。 (Till now you have not specified how many objects you want to keep in QR, so initialization of array is not done yet) (到目前为止,您尚未指定要在QR中保留多少个对象,因此尚未完成数组的初始化)

QR = new Class2[x];

Here you are saying, now i know how many (x many items) objects i will keep in QR, so allocate memory( via new keyword) to QR. 在这里,您说的是,现在我知道我将在QR中保留多少个(x个项目)对象,因此将内存(通过新关键字)分配给QR。

So basically you have just initialized the array with the number of items you will keep in array, ie you have specified the size of array. 因此,基本上,您刚刚使用要保留在数组中的项数来初始化数组,即,您已经指定了数组的大小。

Now class2 object will reside at some index in the QR (index 0 to 9). 现在,class2对象将驻留在QR中的某个索引处(索引0到9)。 Class2 c = QR[0]; // for example

You can create an array of Class2 and initialize it as: 您可以创建一个Class2数组并将其初始化为:

public Class2[] QR;  // Declare the array
public static int x = 10;
QR = new Class2[x];  // Allocate for 10 instances memory 

// Now create the and init the instances
for (int i=0 ; i<QR.lenght ; i++) {
   QR[i] = new Class2();  // Call the constructor
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM