如果问题中的代码不起作用,则可能尚未在类上正确实现。equals(Object)Customer
据推测,有一些密钥(让我们称之为)可以唯一地标识客户;例如:customerId
class Customer {
    private String customerId;
    ...
的适当定义如下所示:equals(Object)
    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);
    }
为了完整性,还应实现,以便两个相等的对象将返回相同的哈希值。上述定义的匹配项为:hashCodeCustomerhashCodeequals
    public int hashCode() {
        return customerId.hashCode();
    }
还值得注意的是,如果列表很大,这不是删除重复项的有效方法。(对于包含 N 个客户的列表,您需要在最坏的情况下执行比较;即,当没有重复项时。为了获得更有效的解决方案,您可以使用 进行重复检查。另一种选择是使用Tom Hawtin的答案中解释的a。N*(N-1)/2HashSetLinkedHashSet