There was no blog about behavior confirmation, so a memo.
Below you can see what you can see on the API.
public E pop()
Removes the first object on the stack and returns that object as the value of the function Return value: The object at the top of the stack (the last item in the Vector object). Exception: EmptyStackException-if this stack is empty (https://docs.oracle.com/javase/jp/8/docs/api/java/util/Stack.html#pop--)
public E peek()
Fetch the object at the top of the stack. The object is not removed from the stack at this time. Return value: The object at the top of the stack (the last item in the Vector object). Exception: EmptyStackException-if this stack is empty (https://docs.oracle.com/javase/jp/8/docs/api/java/util/Stack.html#peek--)
For peek.java
public static void main(String[] args) {
try {
Stack<String> stack = new Stack();
stack.push("Good Morning!");
stack.push("Hello!");
stack.peek();
stack.stream().forEach(System.out::println);
// Good Morning!
// Hello!
} catch (EmptyStackException e) {
System.out.println("stack is empty");
}
}
In the case of pop.java
public static void main(String[] args) {
try {
Stack<String> stack = new Stack();
stack.push("Good Morning!");
stack.push("Hello!");
stack.pop();
stack.stream().forEach(System.out::println);
// Good Morning!
} catch (EmptyStackException e) {
System.out.println("stack is empty");
}
}
If pop, it is pushed from the stack, and peek is not pushed from the stack. If you look at peek's API, it will return a return value, so you can pop while verifying the value.
Pop while verifying.java
public static void main(String[] args) {
try {
Stack<String> stack = new Stack();
stack.push("Good Morning!");
stack.push("Hello!");
if (stack.peek().equals("Hello!")) {
stack.pop();
}
System.out.println(stack.peek());
// Good Morning!
} catch (EmptyStackException e) {
System.out.println("stack is empty");
}
}
Recommended Posts