Let's say I have this code in Java:
HashSet<String> wordSet = new HashSet<String>(); String a = "hello"; String b = "hello"; wordSet.add(a);
Would wordSet.contains(b);
return true
or false
? From what I understand, a
and b
refer to different objects even though their values are the same. So contains()
should return false
. However, when I run this code, it returns true
. Will it always return true
no matter where String object b
is coming from as long as b
contains the value "hello"
? Am I guaranteed this always? If not, when am I not guaranteed this? And what if I wanted to do something similar with objects other than Strings?
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 contains() Method in JavaHashSet. 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.
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
The equals() method of java. util. HashSet class is used verify the equality of an Object with a HashSet and compare them. The list returns true only if both HashSet contains same elements, irrespective of order.
It uses equals()
to compare the data. Below is from the javadoc for Set
adds the specified element e to this set if the set contains no element e2 such that (e==null ? e2==null : e.equals(e2)).
The equals()
method for String does a character by character comparison. From the javadoc for String
The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object
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