繁体   English   中英

将对象传递给ArrayList Java

[英]Passing objects to an ArrayList Java

我试图将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));
}

DVD类应该重写toString()方法,然后您必须在其中创建要在输出中看到的String。

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

每次您呼叫system.out.priontln(inventory.get(i))时,都会返回“我是DvD”;

那意味着你会做类似的事情

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

当您拥有Dvd类时,将在构造函数中初始化的8个字段设为私有,然后为这些字段实现getter

然后在实现类中,将arraylist创建为:

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

然后将已初始化的对象添加到列表中。 然后,可以通过将列表迭代为来从列表中获取值:

for(Dvd dvd : inventory)

dvd将为您提供dvd对象,然后只需对其调用getter

解决了,简单的错误,无法调用super()

= /

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM