java中的ArrayList,只执行一次操作
出于某种原因,我在这个问题上画了一个空白。我有一个包含 CD 的 ArrayList(其中一些名称相同),我想打印一个字符串来告诉我每张 CD 有多少张。例如,字符串“您有:(1) AlbumOne、(2) AlbumTwo、(1) AlbumThree”等。CD 未排序。我该怎么做?
For some reason, I'm drawing a blank on this one. I have an ArrayList that contains CDs (some of them identical in name) and I want to print a String that tells how many I have of each CD. For example, a string that says "You have: (1) AlbumOne, (2) AlbumTwo, (1) AlbumThree" etc. The CDs are not sorted. How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一种方法是循环遍历数组,并使用将对象用作键、将值用作计数的映射。因此
,当您循环遍历数组时,请在数组中当前对象的计数器上执行
get
操作。如果得到 null,则将映射中该存储桶的值初始化为 1。如果有值,则递增它。然后您可以循环地图以获取读数。请注意,如果您使用
Hashmap
,您的对象必须正确实现hashcode
和equals
方法。您不必使用您的对象,如果它有键或其他一些区分字段,则地图中的键可以是......One way to do it is to loop thru the array, and use a map that uses the objects as keys and the values as counts. So
As you loop thru the array, do a
get
on the counter for the current object in the array. If you get null, initialize the value at that bucket in the map to be 1. If you have a value, increment it. Then you can loop over the map to get your readout.Note that if you use a
Hashmap
, your objects have to implement thehashcode
andequals
method properly. You don't have to use your object, if it has keys or some other distinguishing field, the keys in your map can be that...不要对
地图
感到困惑。使用Map
适合解决此类问题(正如您所发布的),因此请访问 此 链接(教程)并阅读/了解地图。Don't get confused about the
Map
. Use ofMap
is appropriate to solve such a problem (as you have posted) So please visit this link (tutorial) and read/learn about Map.