sandy
sandy

Reputation: 11

how to remove user defined objects from java arraylist

how can I remove duplicate objects from below list with using hashset. Can you please help without using equals method

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

        //???
    }
}

Upvotes: 1

Views: 895

Answers (2)

Istiaque Hossain
Istiaque Hossain

Reputation: 2367

you can try my code .... firstly change you Customer class and add two override method

add this code on your Customer class

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

and inside your main method

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

Upvotes: 0

AxelH
AxelH

Reputation: 14572

To answer your question :

how can I remove duplicate objects from below list with using hashset. Can you please help without using equals method

HashSet.add requires the method equals to compare elements... so you can't.

public boolean add(E e)

Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.

Upvotes: 1

Related Questions