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]
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
}
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".
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