英文:
What collection do I need to store an Object and it's quantity?
问题
我需要在一个集合中存储产品(对象)及其数量,以便在需要时可以增加每个产品的数量。
在这种情况下,哪种集合类型适用且最好使用?
英文:
I need to store the Product (Object), and it's quantity in a Collection, where I will be able to increase the quantity of each product whenever needed.
What Collection type will work and is best to use in this case?
答案1
得分: 4
我会使用一个Map,例如一个HashMap。地图的键应该是产品的键,值是产品的数量。
英文:
I would use a Map, for example a HashMap. The map key should be the key of the product and the value is the quantity of the product.
答案2
得分: 1
如果数量仅仅是一个计数,而且如果你愿意使用第三方库,你可以使用来自Eclipse Collections的Bag
。Bag
是一个无序且允许重复的Collection
。在内部,一个HashBag
通常是通过HashMap
来实现的,其中键与它们的计数关联。在Eclipse Collections中的HashBag
的情况下,后端存储是一个ObjectIntHashMap
。这样做的好处是,与将键映射到java.util.HashMap
中的计数相比,不需要对Integer
对象进行装箱和拆箱。
Product product1 = Product.of("abc");
Product product2 = Product.of("xyz");
MutableBag<Product> counts = Bags.mutable.empty();
counts.addOccurrences(product1, 5);
counts.addOccurrences(product2, 10);
Assert.assertEquals(5, counts.occurrencesOf(product1));
Assert.assertEquals(10, counts.occurrencesOf(product2));
这里有一篇博客文章更详细地描述了Bag
。
注意:我是Eclipse Collections的一名贡献者。
英文:
If the quantity is simply a count, and if you're open to using a third-party library, you could use a Bag
from Eclipse Collections. A Bag
is a Collection
that is unordered and allows duplicates. Internally, a HashBag
is usually implemented with a HashMap
, with keys associated to their counts. In the case of HashBag
in Eclipse Collections, the backing store is an ObjectIntHashMap
. This has the advantage of not having to box and unbox the Integer
objects as you might if you map keys to their counts in a java.util.HashMap
.
Product product1 = Product.of("abc");
Product product2 = Product.of("xyz");
MutableBag<Product> counts = Bags.mutable.empty();
counts.addOccurrences(product1, 5);
counts.addOccurrences(product2, 10);
Assert.assertEquals(5, counts.occurrencesOf(product1));
Assert.assertEquals(10, counts.occurrencesOf(product2));
Here is a blog that describes Bag
in more detail.
Note: I am a committer for Eclipse Collections
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论