对象添加到自定义类的数组 [英] Add an object to an Array of a custom class
本文介绍了对象添加到自定义类的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是一个初学者到Java和我试图创建一个自定义类的数组。
让说我有一个汽车类打电话,我想创建汽车的数组称为车库。我怎样才能每辆车添加到车库?这是我有:
汽车雷德卡=新车(红楼梦);
车库[] =新的汽车[100];
车库[0] =雷德卡;
解决方案
如果你想使用一个数组,你必须保持它包含的汽车在车库里数的计数器。更好地使用的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);
这篇关于对象添加到自定义类的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文