HR1
HR1

Reputation: 527

Java contains() method returns False even though overridden equals() returns True

I have an class called Record that consists of a vector of Data class objects.

Class Data has nothing but two fields:

Object value;
String name;

I override the equals method in the Record class as follows:

public boolean equals(Object obj) {
    boolean check = true;
    for (int i = 0; i < this.columnsOfData.size();i++) {
        System.out.println( ((Record) obj).columnsOfData.get(i).name + " OBJECT " + ((Record) obj).columnsOfData.get(i).value );
        System.out.println( columnsOfData.get(i).name + " THIS " + columnsOfData.get(i).value );
        if( !((((Record) obj).columnsOfData.get(i).name).equals(this.columnsOfData.get(i).name))   || !((((Record) obj).columnsOfData.get(i).value).equals(this.columnsOfData.get(i).value))) {
            check = false;
        }
    }
    
    return (obj instanceof Record && check);
}

I initialize HashSet as follows:

Set<Record> answer = new HashSet<Record>()

and start testing

        Record r1 = new Record();
        r1.columnsOfData.add(new Data(new Double( 1.5 ),"gpa"));
        r1.columnsOfData.add(new Data(new String("John"),"name"));
        r1.columnsOfData.add(new Data(new Integer( 2 ),"id"));
        
        Record r2 = new Record();
        r2.columnsOfData.add(new Data(new Double( 1.5 ),"gpa"));
        r2.columnsOfData.add(new Data(new String("John"),"name"));
        r2.columnsOfData.add(new Data(new Integer( 2 ),"id"));

        System.out.println(r1.equals(r2)); //RETURNS TRUE
        answer.add(r1);
        System.out.println(answer.contains(r2)); //RETURNS FALSE

Any help understanding where the issue is would be greatly appreciated.

Upvotes: 0

Views: 670

Answers (2)

sparik
sparik

Reputation: 1201

HashSet relies on the contract that hashCodes of equal objects are equal. That is, if a.equals(b) returns true, then a.hashCode() must be the same as b.hashCode()

You should override the hashCode() method of Record to use it in a HashSet

Upvotes: 0

Antonio Acquavia
Antonio Acquavia

Reputation: 11

Try to override also the hashCode method. It should work. You can find an explanation here: HashSet contains() method

Upvotes: 1

Related Questions