如何从列表中删除重复项? [英] How to remove duplicates from a list?
问题描述
我想从列表中删除重复项,但我所做的不起作用:
I want to remove duplicates from a list but what I am doing is not working:
List<Customer> listCustomer = new ArrayList<Customer>();
for (Customer customer: tmpListCustomer)
{
if (!listCustomer.contains(customer))
{
listCustomer.add(customer);
}
}
推荐答案
如果您问题中的代码不起作用,您可能没有在 Customer 上实现
equals(Object)
适当地分类.
If the code in your question doesn't work, you probably have not implemented equals(Object)
on the Customer
class appropriately.
大概有一些唯一标识客户的密钥(让我们称之为customerId
);例如
Presumably there is some key (let us call it customerId
) that uniquely identifies a customer; e.g.
class Customer {
private String customerId;
...
equals(Object)
的适当定义如下所示:
An appropriate definition of equals(Object)
would look like this:
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Customer)) {
return false;
}
Customer other = (Customer) obj;
return this.customerId.equals(other.customerId);
}
为了完整性,您应该还实现hashCode
,以便两个相等的Customer
对象将返回相同的哈希值.与上述 equals
定义匹配的 hashCode
将是:
For completeness, you should also implement hashCode
so that two Customer
objects that are equal will return the same hash value. A matching hashCode
for the above definition of equals
would be:
public int hashCode() {
return customerId.hashCode();
}
还值得注意的是,如果列表很大,这不是删除重复项的有效方法.(对于包含 N 个客户的列表,您将需要在最坏的情况下执行 N*(N-1)/2
比较;即,当没有重复项时.)对于更有效的解决方案,您应该使用类似 HashSet
的东西来做重复检查.
It is also worth noting that this is not an efficient way to remove duplicates if the list is large. (For a list with N customers, you will need to perform N*(N-1)/2
comparisons in the worst case; i.e. when there are no duplicates.) For a more efficient solution you should use something like a HashSet
to do the duplicate checking.
这篇关于如何从列表中删除重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!