Keval Trivedi Keval Trivedi - 2 months ago 15
Java Question

Remove element from HashSet

First of all add the element in HashSet and prints the size of HashSet which returns as expected. but i modified one of the object value and again store in to HashSet and remove the object using object name. but still i get the same size as previous. My code is as under :

public class Test {

private String s;
public Test(String s){
this.s = s ;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<Object> hs = new HashSet<Object>();
Test t1 = new Test("Keval");
Test t2 = new Test("Keval");

String s1 = new String("Keval");

hs.add(t1);
hs.add(t2);
hs.add(s1);
System.out.println("Set Size :: " + hs.size());

s1 = new String("Demo");
hs.remove(s1);
System.out.println("Set Size :: " + hs.size());


}
}


Output of above code is :

Set Size :: 3
Set Size :: 3 // Why it prints 3 insted of 2???

Answer
    s1 = new String("Demo");        
    hs.remove(s1);

This doesn't remove an existing element from the HashSet. It attempts to remove an object not in the Set, and therefore does nothing.

If you remove the s1 = new String("Demo"); line, s1 still refers to the String that was added to the Set, so hs.remove(s1) removes that String from the Set.