Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashSet contains method, strange behavior [duplicate]

Tags:

java

here is my code :

public class testGui {



    public static void main(String[] arg){
        class TESTS{
            String t;

            public TESTS(String t){
                this.t = t;
            }

            @Override
            public boolean equals(Object x){
                System.out.println("My method is called...");
                if(x instanceof TESTS){
                    TESTS zzz = (TESTS) x;
                    return zzz.t.compareTo(t)==0;
                }
                else return false;
            }
        }
        HashSet<TESTS> allItems = new HashSet<TESTS>();
        allItems.add(new TESTS("a"));
        allItems.add(new TESTS("a"));
        System.out.println(allItems.contains(new TESTS("a")));
    }

}

I do not get why the hashset contains method is not calling my equals method as mentionned in their specifications :

More formally, adds the specified element, o, to this set if this set contains no element e such that (o==null ? e==null : o.equals(e))

My code is returning false and not going into my equals method.

Thanks a lot for answering!

like image 473
Abbadon Avatar asked Mar 31 '11 19:03

Abbadon


People also ask

Does HashSet have Contains method?

HashSet. contains() method is used to check whether a specific element is present in the HashSet or not. So basically it is used to check if a Set contains any particular element. Parameters: The parameter element is of the type of HashSet.

Can HashSet have duplicate objects?

HashSets are used to store a collection of unique elements. HashSet cannot contain duplicate values. HashSet allows null value. HashSet is an unordered collection.

How does HashSet contains method work?

The purpose of the contains method is to check if an element is present in a given HashSet. It returns true if the element is found, otherwise false. Whenever an object is passed to this method, the hash value gets calculated. Then, the corresponding bucket location gets resolved and traversed.


1 Answers

When you override equals, you must also override hashCode. Otherwise, equal objects will have different hash codes and be considered unequal.

It is also strongly recommended not to override only hashCode. But this is not essential, as unequal objects can have the same hash code.

like image 101
Matthew Flaschen Avatar answered Oct 14 '22 15:10

Matthew Flaschen