Skip to content

Instantly share code, notes, and snippets.

@ipekt
Created December 18, 2018 10:06
Show Gist options
  • Select an option

  • Save ipekt/0119085aacf432e745406ee1377b1d82 to your computer and use it in GitHub Desktop.

Select an option

Save ipekt/0119085aacf432e745406ee1377b1d82 to your computer and use it in GitHub Desktop.
public class Stack<E> {
private E[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
public Stack() {
elements = (E[]) new Object[DEFAULT_INITIAL_CAPACITY];
}
public void push(E e) {
ensureCapacity();
elements[size++] = e;
}
public E pop() {
if (size == 0) {
throw new EmptyStackException();
}
E result = elements[--size];
elements[size] = null; // Eliminate obsolete reference
return result;
}
public boolean isEmpty() {
return size == 0;
}
private void ensureCapacity() {
if (elements.length == size) elements = Arrays.copyOf(elements, 2 * size + 1);
}
public void pushAll(Iterable<? extends E> src) {
for (E e : src) {
push(e);
}
}
public void popAll(Collection<? super E> dst) {
while (!isEmpty()) {
dst.add(pop());
}
}
}
interface ServiceError {}
class AnotherValidationError implements ServiceError {
String name;
public AnotherValidationError(String name) {
this.name = name;
}
}
class ValidationError extends AnotherValidationError {
String name;
public ValidationError(String name) {
super(name);
}
}
// Works
public void test1() {
Stack<Integer> numberStack = new Stack<Integer>();
Collection<Number> objects = Arrays.asList(1, 2);
numberStack.popAll(objects);
}
// Works
public void test2() {
Stack<ValidationError> stack = new Stack<ValidationError>();
Collection<ServiceError> objects =
Arrays.asList(new ValidationError("A"), new ValidationError("B"));
stack.popAll(objects);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment