查找数组列表中的重复值
我有一个 ArrayList
例如
class Car{
String carName;
int carType;
}
现在,我必须查找列表中是否有任何具有相同名称的汽车。最好的方法是什么?
I have an ArrayList<Car>
For Example
class Car{
String carName;
int carType;
}
Now, I have to find if the list has any cars having same name. What is the best way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
创建一个比较器:
现在将
ArrayList
的所有汽车添加到SortedSet
,最好是TreeSet
;如果有重复项,请添加到重复项列表中:最后,在您的
重复项
中,您将拥有所有重复项。Create a comparator:
Now add all the cars of the
ArrayList
to aSortedSet
, preferablyTreeSet
; if there are duplicates add to the list of duplicates:Finally in your
duplicates
you will have all the duplicates.如果你有
并且
包含一个汽车列表,那么你可以有一个方法,比如
找出汽车列表中是否有名称重复的汽车。
If you have
and
that contains a list of cars, then you could have a method like
to find out whether the list of cars have cars with duplicate names.
试试这个:
注意:这将为您提供重复的汽车名称。下一步将从列表中提取具有这些名称的所有汽车(如果您需要汽车对象)
Try this:
Note: this will give you the car names that are duplicate. A follow on would be extracting all cars with those names from the list (if you need the Car objects)
重写
Car
类中的equals()
和hashCode()
方法并使用Set
实现,例如HashSet
而不是ArrayList
。Override
equals()
andhashCode()
methods in yourCar
class and use aSet
implementation such asHashSet
instead ofArrayList
.我做了一个类似的程序,它向您显示在 ArrayList 中重复的单词(还显示了 arraylist 内容和较大的字符串)
哦,顺便说一句,变量和其他内容(如注释)都是西班牙语的,因为我说西班牙语: / 但是,如果你看到代码,你会发现我用 2 个 bucles 解决了这个问题!
这是我的输出:
I did a similiar program that shows you the words that where repeated in an ArrayList (also it shows the arraylist content and the larger string)
Oh, by the way, variables, and other stuff like comments are in spanish, cause I speak spanish:/ but, if you see the code you can see that I resolved the problem with 2 bucles for!
This is my output: