SP6
SP6

Reputation: 119

strange HashSet behavior

This is part of my implementation

aFList = new HashSet<Fault>();
bFList = new HashSet<Fault>();
oFList = new HashSet<Fault>();

temp.addAll(aFList);
temp.addAll(bFList);
oFList.addAll(temp);

Fault Class is as follows

public class Fault {
    int nodeIndex;
    boolean val;
}

Display() {
    Object [] temp;
    temp = aFList2.toArray();
    for(int i=0;i<temp.length;i++)
        ((Fault) temp[i]).display();
}

Results:

14_true 
6_true 
17_false 
16_false 
16_false 
9_false 
14_true 

Question: Why do I get repeated list elements? It might be because oFList already contained those elements but I thought a HashSet would take care of duplicates. Am I missing something?

Upvotes: 1

Views: 90

Answers (1)

Paul Tomblin
Paul Tomblin

Reputation: 182762

If you're going to put a class in a HashMap or HashSet, you MUST implement equals() and hashCode().

Upvotes: 4

Related Questions