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
.
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.
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.
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. 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.
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 false
always in the case of contains()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With