如何在Java中声明对象数组? [重复]

时间:2021-12-27 21:26:44

Possible Duplicate:
How to declare an array in Java?

可能重复:如何在Java中声明数组?

Suppose I have an object car (class vehicle) and I want to create an array of N number of cars . How do I declare that in Java?

假设我有一辆物品车(类车),我想创建一组N辆车。我如何在Java中声明?

vehicle[N]= car=new vehicle [];

Is this right?

这是正确的吗?

4 个解决方案

#1


15  

It's the other way round:

反过来说:

Vehicle[] car = new Vehicle[N];

This makes more sense, as the number of elements in the array isn't part of the type of car, but it is part of the initialization of the array whose reference you're initially assigning to car. You can then reassign it in another statement:

这更有意义,因为数组中的元素数量不是汽车类型的一部分,但它是数组初始化的一部分,该数组的初始化指定给汽车。然后,您可以在另一个语句中重新分配它:

car = new Vehicle[10]; // Creates a new array

(Note that I've changed the type name to match Java naming conventions.)

(请注意,我已更改类型名称以匹配Java命名约定。)

For further information about arrays, see section 10 of the Java Language Specification.

有关数组的更多信息,请参阅Java语言规范的第10节。

#2


3  

Like this

喜欢这个

Vehicle[] car = new Vehicle[10];

车辆[]车=新车[10];

#3


2  

vehicle[] car = new vehicle[N];

#4


0  

This is the correct way:

这是正确的方法:

You should declare the length of the array after "="

你应该在“=”之后声明数组的长度

Veicle[] cars = new Veicle[N];

#1


15  

It's the other way round:

反过来说:

Vehicle[] car = new Vehicle[N];

This makes more sense, as the number of elements in the array isn't part of the type of car, but it is part of the initialization of the array whose reference you're initially assigning to car. You can then reassign it in another statement:

这更有意义,因为数组中的元素数量不是汽车类型的一部分,但它是数组初始化的一部分,该数组的初始化指定给汽车。然后,您可以在另一个语句中重新分配它:

car = new Vehicle[10]; // Creates a new array

(Note that I've changed the type name to match Java naming conventions.)

(请注意,我已更改类型名称以匹配Java命名约定。)

For further information about arrays, see section 10 of the Java Language Specification.

有关数组的更多信息,请参阅Java语言规范的第10节。

#2


3  

Like this

喜欢这个

Vehicle[] car = new Vehicle[10];

车辆[]车=新车[10];

#3


2  

vehicle[] car = new vehicle[N];

#4


0  

This is the correct way:

这是正确的方法:

You should declare the length of the array after "="

你应该在“=”之后声明数组的长度

Veicle[] cars = new Veicle[N];