Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Would a Java HashSet<String>'s contains() method test equality of the strings or object identity?

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?

like image 841
OkonX Avatar asked Jan 23 '12 05:01

OkonX


People also ask

How do you check if a HashSet contains a value in Java?

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.

Does HashSet have Contains method?

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.

Does HashSet call equal?

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.

Does HashSet use equals or Compareto?

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.


1 Answers

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

like image 170
Aravind Yarram Avatar answered Sep 17 '22 16:09

Aravind Yarram