java 在java中创建数组并在构造函数中初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15729846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:40:10  来源:igfitidea点击:

Creating arrays in java and initialising in constructor

javaarraysconstructor

提问by friendlycow

I need to create an array of objects (Cars) and then initialise the array to be of a required size (10) within a constructor. So far I have this:

我需要创建一个对象数组 (Cars),然后在构造函数中将数组初始化为所需大小 (10)。到目前为止,我有这个:

public class Queue {

    private Car [] car;

    public Queue (Car [] car) {
        Car [] car = new Car[10];
    }   
}

Which when I compile says it cannot find the Car symbol. I'm presuming the problem is with the creation of the array as I don't seem to have created the Car properly. Any help would be appreciated <3

当我编译时说它找不到 Car 符号。我假设问题出在数组的创建上,因为我似乎没有正确创建 Car。任何帮助将不胜感激 <3

回答by rabz100

This is the proper way to create it.

这是创建它的正确方法。

public class Queue {
    private Car [] car;
    public Queue () {
       car = new Car [10];
    }   
}

Provided that you have defined the car class.

前提是您已经定义了汽车类。

回答by Lokesh

Create a Car Class and put it in classpath and it will work smoothly .

创建一个 Car Class 并将其放在 classpath 中,它将顺利运行。

EDIT[2nd time]: editing my code as per commments below. This shld work

编辑[第二次]:根据下面的评论编辑我的代码。这应该有效

public class Queue {

    private Car [] mycar;

    public Queue (Car [] car) {
        mycar = car;
    }   
}

EDIT:

编辑:

class Car {

}