ArrayList的在Java中,只是在做一个动作一次 [英] ArrayList in java, only doing an action once

查看:65
本文介绍了ArrayList的在Java中,只是在做一个动作一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某些原因,我画在这一个空白。我有一个包含光盘(其中一些在名字相同)的一个ArrayList,我想打印一个字符串,告诉我有多少每个CD的。例如,说一个字符串你有:(1)AlbumOne,(2)AlbumTwo,(1)AlbumThree等不排序的光盘。我怎样才能做到这一点?

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?

推荐答案

要做到这一点是循环数组THRU,并用它使用对象作为键和值作为计数地图的方法之一。因此,

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

Map<YourObject, Integer> counter ...

当你循环数组THRU,做一个 GET 柜台上的数组中的当前对象。如果你空,在地图上的水桶初始化值是1。如果你有一个值,增加它。然后,你可以循环在地图上,让你的读数。

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.

请注意,如果您使用的Hashmap ,你的对象必须实现散code 正常等于方法。你不必使用对象,如果它有钥匙或一些其它区别字段,在地图中的键可以是...

Note that if you use a Hashmap, your objects have to implement the hashcode and equals 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...

这篇关于ArrayList的在Java中,只是在做一个动作一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆