将对象存储到数组中 - Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33485534/
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
Storing object into an array - Java
提问by Justin C
I am relatively new to Java and I have taken some light courses on it. I am trying to emulate an exercise that I had a while back and I am having some trouble.
我对 Java 比较陌生,我已经学习了一些关于它的轻松课程。我正在尝试模拟一段时间前的一项练习,但遇到了一些麻烦。
I have two classes. One is taking in data and the other is storing it.
我有两节课。一个是接收数据,另一个是存储数据。
public class Car{
public Car(String name, String color)
{
this.name = name,
this.color = color
}
How can I store this into the array (not an array list) that I created in this class:
如何将其存储到我在此类中创建的数组(不是数组列表)中:
public class CarDatabase {
Car[] carList = new Car[100];
public CarDatabase()
{
// System.out.println("test");
}
public void createAccount(String name, String color)
{
// this is where I am having trouble
for (int i = 0; i < carList.length; i++)
{
System.out.println("Successfully created: " + name +
"." + "Color of car: " + color);
break;
}
}
I don't have a main method yet but I will need one later on to for example, PRINT out this array and that is what I can't wrap my head around - how do I store DATA/OBJECTS into the "CarDatabase" array so I can call methods with it later (instead of just being able to print it)?
我还没有主要方法,但我稍后需要一个方法,例如,打印出这个数组,这就是我无法解决的问题 - 如何将数据/对象存储到“CarDatabase”数组中所以我以后可以用它调用方法(而不仅仅是能够打印它)?
Any help would be appreciated. Thanks!
任何帮助,将不胜感激。谢谢!
回答by aandis
Not really sure what you are trying to achieve but I'll give it a go.
不太确定你想要实现什么,但我会试一试。
You could modify your CarDatabase
class like so -
你可以CarDatabase
像这样修改你的类 -
public class CarDatabase {
Car[] carList = new Car[100];
int carsStored;
// No need for a constructor since we don't need any initialization.
// The default constructor will do it's job.
public void createAccount(String name, String color) {
carList[carsStored++] = new Car(name, color);
}
}
And your main method could look like -
你的主要方法可能看起来像 -
public static void main(String[] args) {
CarDatabase database = new CarDatabase();
database.createAccount("Lambo", "Red");
database.createAccount("Punto", "White");
// To loop through your database, you can then do
for(int i = 0; i < database.carList.length; i++) {
Car car = database.carList[i];
// Now you can call methods on car object.
}
}
Hope that helps.
希望有帮助。