Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/main/java/collections/stack/Stack.java
Original file line number Diff line number Diff line change
@@ -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];
}
}
62 changes: 62 additions & 0 deletions src/test/java/collections/stack/StackTest.java
Original file line number Diff line number Diff line change
@@ -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());
}

}