diff --git a/src/main/java/collections/stack/Stack.java b/src/main/java/collections/stack/Stack.java new file mode 100644 index 0000000..3ef7f99 --- /dev/null +++ b/src/main/java/collections/stack/Stack.java @@ -0,0 +1,35 @@ +package collections.stack; + +import collections.exception.OverflowException; +import collections.exception.UnderflowException; + +public class Stack { + private static final int CAPACITY = 10; + + private final int[] elements = new int[CAPACITY]; + private int size = 0; + + public boolean isEmpty() { + return size == 0; + } + + private boolean isFull() { + return size == elements.length; + } + + public void push(int element) { + if (isFull()) { + throw new OverflowException(); + } + + elements[size++] = element; + } + + public int pop() { + if (isEmpty()) { + throw new UnderflowException(); + } + + return elements[--size]; + } +} diff --git a/src/test/java/collections/stack/StackTest.java b/src/test/java/collections/stack/StackTest.java new file mode 100644 index 0000000..eb4636f --- /dev/null +++ b/src/test/java/collections/stack/StackTest.java @@ -0,0 +1,62 @@ +package collections.stack; + +import collections.exception.UnderflowException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class StackTest { + + private Stack stack; + + @BeforeEach + void setUp() { + stack = new Stack(); + } + + @Test + void newStack_IsEmpty() { + Assertions.assertTrue(stack.isEmpty()); + } + + @Test + void afterOnePush_IsNotEmpty() { + stack.push(0); + Assertions.assertFalse(stack.isEmpty()); + } + + @Test + void willThrowUnderflowException_WhenEmptyStackIsPopped() { + Assertions.assertThrows(UnderflowException.class, stack::pop); + } + + @Test + void afterOnePushAndOnePop_WillBeEmpty() { + stack.push(0); + stack.pop(); + Assertions.assertTrue(stack.isEmpty()); + } + + @Test + void afterTwoPushesAndOnePop_WillNotBeEmpty() { + stack.push(0); + stack.push(0); + stack.pop(); + Assertions.assertFalse(stack.isEmpty()); + } + + @Test + void afterPushingX_WillPopX() { + stack.push(42); + Assertions.assertEquals(42, stack.pop()); + } + + @Test + void afterPushingXAndY_WillPopYAndX() { + stack.push(42); + stack.push(100); + Assertions.assertEquals(100, stack.pop()); + Assertions.assertEquals(42, stack.pop()); + } + +} \ No newline at end of file