Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashSet contains() method

I executed below code and found the output was false.

import java.util.Set;
import java.util.HashSet;

public class Name {
    private String first, last;

    public Name(String first, String last) {
        this.first = first;
        this.last = last;
    }

    public boolean equals(Object o) {
        if (!(o instanceof Name))
            return false;
        Name n = (Name) o;
        return n.first.equals(first) && n.last.equals(last);
    }

    public static void main(String[] args) {
        Set<Name> s = new HashSet<Name>();
        s.add(new Name("Donald", "Duck"));
        System.out.println(s.contains(new Name("Donald", "Duck")));
    }
}

I want to know how it behaves and why output is false.

like image 300
Babanna Duggani Avatar asked Jul 17 '15 07:07

Babanna Duggani


People also ask

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.

How do you check if a HashSet contains a value?

The contains() method of Java HashSet class is used to check if this HashSet contains the specified element or not. It returns true if element is found otherwise, returns false.

Why HashSet has no get method?

HashSet does not have any method to retrieve the object from the HashSet. There is only a way to get objects from the HashSet via Iterator. When we create an object of HashSet, it internally creates an instance of HashMap with default initial capacity 16.

Do we have get object o method in HashSet?

Do we have get(Object o) method in HashSet. Explanation: get(Object o) method is useful when we want to compare objects based on the comparison of values. HashSet does not provide any way to compare objects. It just guarantees unique objects stored in the collection.


1 Answers

You need to override hashCode() method also along with equals(). Both the methods are used for proper functionality of HashSet, so must be overriden in a user-defined class if you are making that class as a key, else hashCode() of Object class is getting used and no two different objects can be considered as same as their hashCode() would always be different, and will for sure return falsealways in the case of contains().

like image 159
AnkeyNigam Avatar answered Nov 08 '22 14:11

AnkeyNigam