且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

防止打印多个对象

更新时间:2023-12-01 23:03:16

您可以使用

You could use a HashMap to store all items, mapping Item to quantity.

类似

HashMap<Item,Integer> receipt = new HashMap<Item,Integer>();

将是您的收据数据结构.

will be you receipt data structure.

要检查您的receipt是否已经有特定的商品,例如i,您应该拥有

And to to check if your receipt already has a particular item, say i, you would have

if (receipt.containsKey(i){
    receipt.get(i) += 1; // increment qantity
    // do other stuff to total, taxes etc.
} else { // this is the first time this kind of item is being added
    receipt.put(i, new Integer(1)); // so put it in the map
}

这样,您可以避免重复(HashMap中的所有键都是唯一的).

This way you can avoid duplicates (all keys in HashMaps are unique).

您当然必须在Item类中实现equals方法(例如,当项目名称相等时,项目相等),以让HashMap知道何时两个Item相等(因为它在执行contains检查,它使用对象的equals方法测试是否相等.

You would of course have to implement the equals method in your Item class (for example, items are equal when their names are equal) to let the HashMap know when two Items are equal (because when it performs the contains check, it tests for equality using the object's equals method).