The removeRange() method of Stack in Java is used to remove all elements within the specified range from an Stack object. It shifts any succeeding elements to the left. This call shortens the stack by (toIndex-fromIndex) elements where toIndex is the ending index and fromIndex is the starting index within which all elements are to be removed. (If toIndex==fromIndex, this operation has no effect)
removeRange(int fromIndex, int toIndex)
Parameters: This methid takes two parameters:
- fromIndex: starting index from which index elements are to be removed.
- toIndex: within range[fromIndex-toIndex), all elements are removed.
Return Value: This method does not return any value. It only removes all the elements within the specified range.
Exceptions: This method throws indexOutOfBoundsException if fromIndex or toIndex is out of range (fromIndex = size() or toIndex > size() or toIndex < fromIndex)
Below examples illustrate the Stack.removeRange() method:
Example 1 : Demonstrating the use of removeRange() method
The stack before using removeRange:[1, 2, 3, 12, 9, 13] The stack after using removeRange:[3, 12, 9, 13]
Example 2 : Program to demonstrate error
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.