简体   繁体   English

将对象传递给ArrayList Java

[英]Passing objects to an ArrayList Java

I am trying to pass 5 objects of 3 types into an array list. 我试图将3种类型的5个对象传递到数组列表中。 When I print the list all values are zero. 当我打印列表时,所有值均为零。 I've tried amending the object types but still no result, can anyone help? 我试过修改对象类型,但仍然没有结果,有人可以帮忙吗?

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

And so on.. Now my output looks like this: 依此类推..现在我的输出看起来像这样:

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

Any Suggestions? 有什么建议么?

Code for Adding Objects: 添加对象的代码:

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

Print Code: 打印代码:

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

Your DVD Class should override the toString() Method and there you will have to create the String you want to see in your output. DVD类应该重写toString()方法,然后您必须在其中创建要在输出中看到的String。

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

this would return "I am a DvD" each time you call system.out.priontln(inventory.get(i)); 每次您呼叫system.out.priontln(inventory.get(i))时,都会返回“我是DvD”;

That means you will do something like 那意味着你会做类似的事情

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

As you have the Dvd class make the 8 fields that have initialized in the constructor as private then implement the getters for those fields 当您拥有Dvd类时,将在构造函数中初始化的8个字段设为私有,然后为这些字段实现getter

Then in the implmentation class create the arraylist as : 然后在实现类中,将arraylist创建为:

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

then add the objects initilized to the list. 然后将已初始化的对象添加到列表中。 Then you can obtain the values from the list by iterating the list as : 然后,可以通过将列表迭代为来从列表中获取值:

for(Dvd dvd : inventory)

dvd will give you the dvd objects then just call the getters on it dvd将为您提供dvd对象,然后只需对其调用getter

Got it resolved, simple mistake, failed to call super() 解决了,简单的错误,无法调用super()

=/ = /

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

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