想避免在ArrayList中重复条目 [英] Would like to avoid duplicate entries in a ArrayList

查看:170
本文介绍了想避免在ArrayList中重复条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找像ArrayList这样的对象,它可以让我避免重复的条目。
例如,它可能有一个方法在将每个条目添加到ArrayList之前调用'contains()'来有效。

I am looking for an object like ArrayList that would let me avoid duplicate entries. For example it might have a method that calls 'contains()' to valid each entry before it is added to the ArrayList.

ArrayList<String> al = new ArrayList<String>();
if(!al.contains("red")){
  al.add("red");
}

这样的事情是否存在?

推荐答案

ArrayLists和列表一般不是为避免重复而设计的,它们被设计为一种维护多个元素顺序的集合。如果你想要一个更适合这份工作的集合,你需要一套:

ArrayLists, and Lists in general aren't designed to avoid duplicates, they're designed as a type of collection that maintains the order of a number of elements. If you want a collection more suited for the job then you want a set:

Set<String> set = new HashSet<String>();

然后,您可以将所有想要的内容添加到集合中,它将永远不会包含重复的字符串。请注意,如果你在自己编写的类中使用它,那么你需要实现 equals() hashcode()为此正常工作。

You can then add all you want to the set and it will never contain duplicate strings. Note that if you're using this with a class you wrote yourself then you'll need to implement equals() and hashcode() for this to work properly.

如下面的评论所示,如果您仍然需要维护订单删除重复项,然后 LinkedHashSet 是你的朋友。

As in the comment below, if you do still need to maintain order and remove duplicates, then LinkedHashSet is your friend.

这篇关于想避免在ArrayList中重复条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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