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());
}
}