且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

对象添加到自定义类的数组

更新时间:2022-10-16 16:22:54

如果你想使用一个数组,你必须保持它包含的汽车在车库里数的计数器。更好地使用的ArrayList 而不是数组:

 列表<汽车>车库=新的ArrayList<汽车>();
garage.add(雷德卡);

Im a beginner to Java and I'm trying to create an array of a custom class. Let say I have a class called car and I want to create an array of cars called Garage. How can I add each car to the garage? This is what I've got:

car redCar = new Car("Red");
car Garage [] = new Car [100];
Garage[0] = redCar;

If you want to use an array, you have to keep a counter which contains the number of cars in the garage. Better use an ArrayList instead of array:

List<Car> garage = new ArrayList<Car>();
garage.add(redCar);