RaceBase
RaceBase

Reputation: 18848

addAll to Set is not adding the values in java

I have a property in an Object(Obj1)

Set<AssignedService> serviceList;
public Set<AssignedService> getServiceList();

I am doing the below operation in certain instances

Obj1.getServiceList().clear();
Obj1.getServiceList().addAll(services);

where Services is also Set

But what I see as an end result is services set is having 4 objects/data elements but Obj1.getServiceList() is returning an empty set after addAll

What's the issue here. is it a problem with AssignedService object since it doesn't implements IComparable

Upvotes: 1

Views: 5346

Answers (2)

Anders R. Bystrup
Anders R. Bystrup

Reputation: 16060

You should first read this excellent piece on .equals()

Then, as others have pointed out, check your implementation of equals() and .hashcode() on the AssignedService class. Most likely the root cause is found here.

You could also check the return value of the .addAll(...) call - false would indicate that the underlying Set isn't modified by the method call.

Cheers,

Upvotes: 3

thedayofcondor
thedayofcondor

Reputation: 3876

Check the implementation of equals() in AssignedService.

Set: A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

Upvotes: 0

Related Questions