Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I try to remove element from HashSet which is not present, why it is not giving runtime error?

Tags:

java

hashset

When I try to remove element from HashSet which is not present, why it does not give runtime error? Please see following program on ideone with output.

import java.util.*;
public class HashSetTest2 {
    public static void main(String [] args){
       HashSet hs=new HashSet(); 
       hs.add("B");
       hs.add("A");
       hs.add("D");
       hs.add("E");
       System.out.println(hs);
       hs.add("F");           
       hs.remove("K");// Not present
    }    
}

//Run successfully
output: [D, E, F, A, B]

like image 871
Neelabh Singh Avatar asked Feb 11 '23 15:02

Neelabh Singh


2 Answers

That is how the interface was created: http://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html#remove(java.lang.Object)

If you want to know if the set contained the removed object, just refer to the boolean value, method remove returns.

boolean existed=hs.remove("K");
if (!existed) {
  //You can throw your runtime exception here if you prefer it that way
}
like image 113
maslan Avatar answered Feb 16 '23 03:02

maslan


There are multiple way of telling the caller that some operation succeeded or not. One of those is throwing an exception when it failed, the other one is returning a boolean where true indicates "success" and false "failure".

From the docs:

Returns true if this set contained the element (or equivalently, if this set changed as a result of the call).

Which can be paraphrased as "returns false if no element was found".

like image 45
Jeroen Vannevel Avatar answered Feb 16 '23 02:02

Jeroen Vannevel