我在學習Java方面還很新,我需要一種方法將從某個類構造而來的每個對象放入一個ArrayList中,以便稍後訪問。自動添加構造到ArrayList中的每個Class對象
這裏是我Item
類:
import java.util.ArrayList;
import java.util.*;
public class Item
{
private String name;
private int quantity;
private ArrayList<Item> allItems = new ArrayList<Item>(); //the ArrayList I'm trying to fill with every Item object
/**
* Constructs an item of a given name and quantity
* @param name Item name
* @param quantity How much of an item the player has
*/
public Item(String name, int quantity)
{
this.name = name;
this.quantity = quantity;
}
/**
* @return Item name
*/
public String getItemName()
{
return name;
}
/**
* @return Quantity of the item
*/
public int getQuantity()
{
return quantity;
}
/**
* @return A list of items that have a quantity > 0
*/
public ArrayList<Item> getInventory()
{
ArrayList<Item> inventory = new ArrayList<Item>();
for(Item i : allItems)
{
if(i.getQuantity() > 0)
inventory.add(i);
}
return inventory;
}
}
我怎樣才能每一次添加一個Item
對象allItems
構建的是?
作爲友好評論,總是試圖使用接口,而不是實現,所以不用返回ArrayList的- 返回列表
- ,並且在創建,任務列表
- myList中=新的ArrayList
- ()。原因?如果將來您使用列表接口的不同實現(如LinkedList),則只需更改幾行即可。 –
2013-04-20 12:25:38