[英]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.