我需要能够创建一组能够存储我选择的对象的库存。我有一个ArrayList
个物品,我需要能够存储在这些库存中,这些物品有“物品编号”,“描述”和“价格”。
我的问题是,我可以使用什么来创建这些库存,以便用户能够添加或删除项目(这些项目都来自项目的ArrayList
)。我认为它可行的唯一方法是创建另一个ArrayList
作为库存,但我不知道如何添加/删除对象,因为它们在ArrayList
我有一个main方法,我的ArrayList
和一个带有构造函数,getter,setter和toString
的项类。
答案 0 :(得分:0)
您可以在ArrayList
中添加或删除类对象。以下是一个例子:
import java.util.ArrayList;
public class InventoryHandler {
public static void main(String[] args) {
Inventory inv1 = new Inventory(1,"item1",10.1);
Inventory inv2 = new Inventory(2,"item2",20.1);
Inventory inv3 = new Inventory(3,"item3",30.1);
ArrayList<Inventory> invs = new ArrayList<Inventory>();
//Adding objects
invs.add(inv1);
invs.add(inv2);
invs.add(inv3);
System.out.println("After adding objects");
for(Inventory inv: invs) {
System.out.println("Item: "+inv.getItemNumber()+" Desc: "+
inv.getItemDescription()+" Price: "+inv.getItemPrice());
}
//Removing objects
invs.remove(inv2);
System.out.println("After removing a object");
for(Inventory inv: invs) {
System.out.println("Item: "+inv.getItemNumber()+" Desc: "+
inv.getItemDescription()+" Price: "+inv.getItemPrice());
}
}
}
class Inventory {
private int itemNumber;
private String itemDescription;
private double itemPrice;
public Inventory(int itemNumber, String itemDescription, double itemPrice) {
this.itemNumber = itemNumber;
this.itemDescription = itemDescription;
this.itemPrice = itemPrice;
}
public int getItemNumber() {
return this.itemNumber;
}
public String getItemDescription() {
return this.itemDescription;
}
public double getItemPrice() {
return this.itemPrice;
}
public void setItemNumber(int newItemNumber) {
this.itemNumber = newItemNumber;
}
public void setItemDescription(String newItemDescription) {
this.itemDescription = newItemDescription;
}
public void setItemPrice(double newItemPrice) {
this.itemPrice = newItemPrice;
}
}