class Item {
public final int sku;
public final String desc;
public final type other_fields;
public Item(int s, String d, type fields...) {
// set fields
}
}
或者如果你真的想变得聪明
abstract class Item {
public final int sku
// ....
}
class PinkCurtains extends Item {
public PinkCurtains() {
sku = 129534;
desc = "Adorable Pink Indoor Curtains";
}
}
class FuzzyTowel extends Item {
public FuzzyTowel() {
sku = 874164;
desc = "Machine Washable Fuzzy Towel";
}
}
然后填充您的列表并搜索
ArrayList<Item> catalog = new ArrayList<Item>(0);
for (int i = 0; i < numItems; i++) {
catalog.add(new Item(arg, arg, arg...));
}
// or
catalog.add(new PinkCurtains());
catalog.add(new FuzzyTowel());
for (Item item : catalog) {
if (chosenItem == item.sku) {
// do all your stuff
}
}
它们被称为 Iterables 是有原因的。如果您不想上课,则不必上课。ArrayList 也有搜索方法, contains() 和 indexOf() 例如:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
如果你想在你去的时候填写这些字段,你可以创建一个让你这样做的类:
class Item {
public int id;
public float price;
}
ArrayList<Item> cart = new ArrayList<Item>(0);
do {
Item item = new Item();
item.id = userInput;
item.price = userInput;
cart.add(item);
} while (userInputting);
float total = 0;
for (Item i : cart) {
total += i.price;
}
// using a regular for loop instead of for-each
for (int i = 0; i < cart.size(); i++) {
Item item = cart.get(i);
// or search for something particular
if (item.id == searchID) {
System.out.println("found item " + item.id + " with price $" + item.price);
}
// equivalent to
if (ids[i] == searchID) {
System.out.println("found item " + ids[i] + " with price $" + prices[i]);
}
}
每次用户想要添加一个项目时,您只需创建一个新项目,填写字段并将其添加到列表中。