什么集合适合存储对象及其数量?

huangapple go评论103阅读模式
英文:

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 CollectionsBagBag是一个无序且允许重复的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(&quot;abc&quot;);
Product product2 = Product.of(&quot;xyz&quot;);

MutableBag&lt;Product&gt; 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

huangapple
  • 本文由 发表于 2020年9月21日 01:21:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63981722.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定