Search code examples
javaapireturn-typetreeset

Method remove() of TreeSet type return


So I was looking at the method remove() from the class TreeSet, and the method has e return type boolean. The java api says that if the item we want to remove is in the tree, and is removed than the method returns true. What if the item is not in the tree, or has already been removed, will this method raise an exception? Can I modify the method so that it returns false when the element was not removed?

 remove

 public boolean remove(Object o)
 Removes the specified element from this set if it is present.(...)
 Returns true if this set contained the element (or equivalently, if this set changed as a            result of the call). (This set will not contain the element once the call returns.)

Solution

  • You answered your own question by reading the documentation.

    What if the item is not in the tree, or has already been removed, will this method raise an exception?

    And then the documentation:

    Returns true if this set contained the element

    So it will return false if the set does not contain the element ("not in the tree" and "has already been removed" are in fact the same case)