HashSet.addAll doesn't enforce uniqueness?

P

Paul Tomblin

I'm finding the same object twice in my HashSet, and since I'm building
that HashSet using

Set getSelectedContentItems()
{
Set ciSet = new HashSet();
Iterator chIt = children.iterator();
while (chIt.hasNext())
{
TreeNode child = (TreeNode)chIt.next();
ciSet.addAll(child.getSelectedContentItems());
}
ciSet.add(myContentItem);
return ciSet;
}

I'm wondering if somehow addAll is adding things without enforcing the
Set's constraint against duplicate items. I've already checked that the
class "MyContentItem" class has a "public boolean equals(Object other)"
method.
 
D

Daniel Dyer

I'm finding the same object twice in my HashSet, and since I'm building
that HashSet using

Set getSelectedContentItems()
{
Set ciSet = new HashSet();
Iterator chIt = children.iterator();
while (chIt.hasNext())
{
TreeNode child = (TreeNode)chIt.next();
ciSet.addAll(child.getSelectedContentItems());
}
ciSet.add(myContentItem);
return ciSet;
}

I'm wondering if somehow addAll is adding things without enforcing the
Set's constraint against duplicate items. I've already checked that the
class "MyContentItem" class has a "public boolean equals(Object other)"
method.

Does it also over-ride hashCode(), and are the two methods consistent with
each other?

Dan.
 
T

Thomas Hawtin

Paul said:
I'm finding the same object twice in my HashSet, and since I'm building
^^^^
that HashSet using

Set's constraint against duplicate items. I've already checked that the
class "MyContentItem" class has a "public boolean equals(Object other)"
method.

And an @Override public int hashCode()?

Tom Hawtin
 
P

Paul Tomblin

In a previous article, (e-mail address removed) (Paul Tomblin) said:
Set's constraint against duplicate items. I've already checked that the
class "MyContentItem" class has a "public boolean equals(Object other)"
method.

Thomas and Daniel hit the nail on the head - I forgot to override
hashCode. Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top