使用构造函数参数初始化对象数组

时间:2022-06-29 21:29:02

Lets say I have 2 classes:

可以说我有两节课:

public class Carinfo {

private String Car;
private Carinfo [] value; 

Carinfo (String someCar, int carValue) {

this.car = someCar;
//At this point I want the "int carValue" to initialize private Carinfo [] value
}

The second class creates car objects, for this example I'll do it with an array

第二个类创建汽车对象,对于这个例子,我将使用数组

public class Generatecar {

Carinfo[] mycars = new Carinfo[1];

public Generatecar {

mycars[0] = new Carinfo("Lada", 9000);

}

What I want is to insert the carValue into the private Carinfo [] value; array. How do I initialize the array within the Carinfo constructor?

我想要的是将carValue插入私人Carinfo []值;阵列。如何在Cari​​nfo构造函数中初始化数组?

If I said something that is unclear, please let me know.

如果我说的不清楚,请告诉我。

4 个解决方案

#1


0  

try create Contructor like this:

尝试像这样创建Contructor:

Carinfo (String someCar, int carValue) {
   this.car = someCar;
   this.value = new Carinfo[carValue];     
}

#2


0  

You can set an array variable the same way you set any other variable:

您可以像设置任何其他变量一样设置数组变量:

mycars = new Carinfo[i];

#3


0  

You can initialize the value array in the constructor, the usual way:

您可以通常的方式在构造函数中初始化值数组:

public Carinfo(String someCar, int carValue) {
    this.car = someCar;
    value = new Carinfo[1];
}

But you will run into a problem when you try to put an int in your array of Carinfos. I don't know what other values you plan to put in that array, but you should consider changing its type to int (if that is the only thing you are going to put in it).

但是当你试图在你的Carinfos数组中放入一个int时,你会遇到一个问题。我不知道你计划在该数组中放入什么其他值,但是你应该考虑将它的类型更改为int(如果这是你要放在其中的唯一值)。

#4


0  

value = new Carinfo[carValue];

value = new Carinfo [carValue];

#1


0  

try create Contructor like this:

尝试像这样创建Contructor:

Carinfo (String someCar, int carValue) {
   this.car = someCar;
   this.value = new Carinfo[carValue];     
}

#2


0  

You can set an array variable the same way you set any other variable:

您可以像设置任何其他变量一样设置数组变量:

mycars = new Carinfo[i];

#3


0  

You can initialize the value array in the constructor, the usual way:

您可以通常的方式在构造函数中初始化值数组:

public Carinfo(String someCar, int carValue) {
    this.car = someCar;
    value = new Carinfo[1];
}

But you will run into a problem when you try to put an int in your array of Carinfos. I don't know what other values you plan to put in that array, but you should consider changing its type to int (if that is the only thing you are going to put in it).

但是当你试图在你的Carinfos数组中放入一个int时,你会遇到一个问题。我不知道你计划在该数组中放入什么其他值,但是你应该考虑将它的类型更改为int(如果这是你要放在其中的唯一值)。

#4


0  

value = new Carinfo[carValue];

value = new Carinfo [carValue];