我在学习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