简体   繁体   中英

Initialize object array with constructor parameter

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?

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

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

mycars = new Carinfo[i];

try create Contructor like this:

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

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).

值=新的Carinfo [carValue];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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