将对象添加到自定义类的 Array [英] Add an object to an Array of a custom class

查看:46
本文介绍了将对象添加到自定义类的 Array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Java 的初学者,我正在尝试创建一个自定义类的数组.假设我有一个名为 car 的类,我想创建一个名为 Garage 的汽车数组.如何将每辆车添加到车库?这就是我所拥有的:

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;

推荐答案

如果你想使用数组,你必须保留一个包含车库中汽车数量的计数器.最好使用 ArrayList 而不是数组:

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

这篇关于将对象添加到自定义类的 Array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆