将对象传递给ArrayList Java

时间:2014-06-30 15:01:37

标签: java object arraylist

我正在尝试将3种类型的5个对象传递到数组列表中。当我打印列表时,所有值都为零。我试过修改对象类型但仍然没有结果,有人可以帮忙吗?

//Item is a Class by itself and the 5 objects draw from this but will have 2/3 additional parameters
ArrayList<Item> inventory = new ArrayList<>();

//Item 1
 Dvd dvd1 = new Dvd(1234567, 2001, "Sugar were going down", "15", "Comedy DVD", 2, 180, "Japanese");

//Item 2
 Dvd dvd2 = new Dvd(7654321, 2005, "The only way is up!", "12A", "Comedy DVD", 3, 220, "Greek, Spanish, Italian");

等等..现在我的输出看起来像这样:

ID: 0
Year: 0
Title: 
Classification: 
Genre: 
Return Date: 25/5/2014
Available: true

任何建议?

添加对象的代码:

 inventory.add(dvd1);
 inventory.add(dvd2);

打印代码:

for(int i = 0; i<= inventory.size(); i++){
    System.out.println(inventory.get(i));
}

3 个答案:

答案 0 :(得分:0)

你的DVD类应该覆盖toString()方法,你必须在那里创建你想要在输出中看到的字符串。

public class ....
.....
    public String toString() {
        return "I am a DvD";
    }
}

这将返回&#34;我是一个DvD&#34;每次调用system.out.priontln(inventory.get(i));

这意味着你会做类似

的事情
StringBuilder sb = new StringBuilder("");
sb.append("ID: " + <IDVariable>);
sb.append("\nYear: " + <YearVariable>);   //<<<< \n means new Line
....
return sb.toString(); 

答案 1 :(得分:0)

正如您所拥有的Dvd类一样,将构造函数中初始化的8个字段设为private,然后为这些字段实现getter

然后在implmentation类中创建arraylist:

List<Dvd> inventory = new ArrayList<Dvd>();

然后将已启动的对象添加到列表中。 然后,您可以通过将列表迭代为:

来从列表中获取值
for(Dvd dvd : inventory)

dvd会为您提供dvd个对象,然后只需在其上调用getter

答案 2 :(得分:0)

得到解决,简单的错误,未能调用super()

= /