I have the following.
HashSet<String> set1 = new HashSet<String>();
HashSet<String> set2 = new HashSet<String>();
String strB1 = "B";
String strB2 = "B";
set1.add( "A" );
set1.add( strB1 );
set2.add( strB2 );
set1.removeAll( set2 );
Will set1 end up containing only “A”, or will it contain “B” as well?
HashSetuses object equality (Object.equals), not identity (“reference equals”).Additionally,
HashSetusesObject.hashCodefor the hashing function.Unfortunately, to “know” this, takes a little bit of “reading into” of the documentation and knowing how a hash is implemented. From the documentation for
HashSet.contains:The more general
Setdocumentation says:With very few exceptions, such as
IdentityHashMap, the data-structures in Java work on equality and not identity.Thus, to answer the question, HashSet works on the “String values”.
(This example can be particularly misleading due to String intern’ing, but that doesn’t change the above as identity implies equality even if the converse is not true.)