如何从列表中删除重复项

如何从列表中删除重复项

本文介绍了如何从列表中删除重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从列表中删除重复的邮件,但是我所做的不起作用:

 列表< Customer> listCustomer = new ArrayList< Customer>(); 
(客户:tmpListCustomer)
{
if(!listCustomer.contains(customer))
{
listCustomer.add
}
}


解决方案

该代码不起作用,您可能没有在 Customer 类上适当地实现 equals(Object) p>

大概有一些密钥(让我们称为 customerId )唯一标识一个客户;例如

  class Customer {
private String customerId;
...

看起来像这样:

  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);
}

为了完整起见, c $ c> hashCode ,这样两个相等的 Customer 对象将返回相同的哈希值。 equals 的上述定义的匹配 hashCode 将是:

  public int hashCode(){
return customerId.hashCode();
}

这也是值得注意的,这不是一个有效的方法来删除重复if列表很大。 (对于具有N个客户的列表,您将需要在最差情况下执行 N *(N-1)/ 2 比较;即当没有重复时)。一个更有效的解决方案,你应该使用像 HashSet 来做重复检查。


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);
  }
 }
解决方案

If that code doesn't work, you probably have not implemented equals(Object) on the Customer class appropriately.

Presumably there is some key (let us call it customerId) that uniquely identifies a customer; e.g.

class Customer {
    private String customerId;
    ...

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);
    }

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();
    }

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.

这篇关于如何从列表中删除重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 15:48