|
发表于 2023-11-13 17:37:46
|
显示全部楼层
本楼为最佳答案
- public class GenericStack<T> {
- private List<T> stack;
- public GenericStack() {
- stack = new ArrayList<>();
- }
- public void push(T item) {
- stack.add(item);
- }
- public T pop() {
- if (isEmpty()) {
- throw new EmptyStackException();
- }
- return stack.remove(stack.size() - 1);
- }
- public T peek() {
- if (isEmpty()) {
- throw new EmptyStackException();
- }
- return stack.get(stack.size() - 1);
- }
- public boolean isEmpty() {
- return stack.isEmpty();
- }
- }
复制代码
- import org.junit.Test;
- import static org.junit.Assert.*;
- public class GenericStackTest {
- @Test
- public void testStackOperations() {
- GenericStack<Integer> stack = new GenericStack<>();
- assertTrue(stack.isEmpty());
- stack.push(1);
- assertFalse(stack.isEmpty());
- assertEquals(1, (int) stack.peek());
- stack.push(2);
- assertEquals(2, (int) stack.peek());
- assertEquals(2, (int) stack.pop());
- assertEquals(1, (int) stack.pop());
- assertTrue(stack.isEmpty());
- }
- }
复制代码
该泛型类GenericStack实现了栈的基本功能,包括创建栈、出栈、入栈、获取栈顶元素和判断栈空。测试类GenericStackTest使用JUnit测试了栈的各项操作,确保其功能正常。 |
|