To display the number of elements in a Stack using the mentioned methods:
size( ) - This method returns the number of elements in the Stack. You can call this method on the Stack object to get the size.
Example:
Stack<Integer> stack = new Stack<>();
// Add elements to the stack
stack.push(10);
stack.push(20);
stack.push(30);
int stackSize = stack.size();
System.out.println("Number of elements in the stack: " + stackSize);
java复制成功复制代码
isEmpty( ) - This method checks if the stack is empty. It returns true if the stack is empty and false otherwise.
Example:
Stack<Integer> stack = new Stack<>();
boolean isStackEmpty = stack.isEmpty();
System.out.println("Is the stack empty? " + isStackEmpty);
java复制成功复制代码
peek() - This method returns the element at the top of the Stack without removing it. If the stack is empty, it will throw an EmptyStackException.
Example:
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
// Get the element at the top of the stack
int topElement = stack.peek();
System.out.println("Element at the top of the stack: " + topElement);
java复制成功复制代码