繁体   English   中英

如何从java arraylist中删除用户定义的对象

[英]how to remove user defined objects from java arraylist

如何使用哈希集从下面的列表中删除重复的对象。 你能在不使用equals方法的情况下提供帮助吗

public class Duplicate {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        List<Customer> customers = new ArrayList<>();
        customers.add(new Customer(1, "Jack"));
        customers.add(new Customer(2, "James"));
        customers.add(new Customer(3, "Kelly"));
        customers.add(new Customer(3, "Kelly"));
        customers.add(new Customer(3, "Kelly"));

        //???
    }
}

回答你的问题:

如何使用哈希集从下面的列表中删除重复的对象。 你能在不使用equals方法的情况下提供帮助吗

HashSet.add需要方法equals来比较元素......所以你不能。

公共布尔添加(E e)

如果指定的元素尚不存在,则将其添加到此集合中。 更正式地,如果该集合不包含元素 e2 使得 (e==null ? e2==null : e.equals(e2))则将指定的元素 e 添加到该集合中 如果此集合已包含该元素,则调用将保持该集合不变并返回 false。

你可以试试我的代码......首先改变你的客户类并添加两个覆盖方法

将此代码添加到您的Customer类上

@Override
    public boolean equals(Object obj) {
        if (obj instanceof Customer) {
            Customer temp = (Customer) obj;
            if (this.id.intValue() == temp.id.intValue() && this.name.equals(temp.name)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int hashCode() {
        return (this.id.hashCode() + this.name.hashCode());
    }  

在你的主要方法中

List<Customer> customers = new ArrayList<>();
        customers.add(new Customer(1, "Jack"));
        customers.add(new Customer(2, "James"));
        customers.add(new Customer(3, "Kelly"));
        customers.add(new Customer(3, "Kelly"));
        customers.add(new Customer(3, "Kelly"));
        //--------------------------------
        Set<Customer> set = new HashSet<>();
        set.addAll(customers);
        customers = new ArrayList<>();
        customers.addAll(set);
        //--------------------------------
        for (Customer customer : customers) {
            System.out.println(customer.getName());
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM