-1

im using Contains method to evaluate customer1 set has cust object, but its keep on adding the same object(its not checking any duplicate)

 `List<Customer> customers = new ArrayList<Customer>();`
    `customers.add(new Customer(1, "A"));`
    `customers.add(new Customer(2, "B"));`
    `customers.add(new Customer(1, "B"));`
    `customers.add(new Customer(1, "C"));`
    `customers.add(new Customer(2, "A"));`
    `customers.add(new Customer(2, "B"));`
    `customers.add(new Customer(1, "A"));`
    `customers.add(new Customer(2, "C"));`
    `Set<Customer> customers1 = new HashSet<Customer>();`
    `for(Customer cust: customers) {`
        `if(!customers1.contains(cust)) {`
         `   customers1.add(cust);`
        `}`
    `}`

Expected Output:

[Customer{id=1, name='A'}, Customer{id=1, name='B'}, Customer{id=1, name='C'}, Customer{id=2, name='A'}, Customer{id=2, name='B'}]

2 Answers2

0

contains() internally calls equals() method to check for the identity so you have to overide equals() along with hashcode() method to check for Identity.

Below link will help you:

Why do I need to override the equals and hashCode methods in Java?

Pradeep
  • 1,192
  • 2
  • 12
  • 30
0

First of all, you could just do

Set<Customer> customers1 = new HashSet<>(customers);

but your issue is mostlikely because your not overriding equals, hashcode

Suic
  • 433
  • 1
  • 3
  • 9