Skip to content

Instantly share code, notes, and snippets.

@ipekt
Last active December 18, 2018 10:27
Show Gist options
  • Select an option

  • Save ipekt/3a097c343009c2702b15668d3cec7603 to your computer and use it in GitHub Desktop.

Select an option

Save ipekt/3a097c343009c2702b15668d3cec7603 to your computer and use it in GitHub Desktop.
public class YetAnotherStack<E> {
private List<? super E>[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
public YetAnotherStack() {
elements = (List<? super E>[]) new Object[DEFAULT_INITIAL_CAPACITY];
}
public boolean isEmpty() {
return size == 0;
}
public List<? super E> pop() {
if (size == 0) throw new EmptyStackException();
List<? super E> result = elements[--size];
elements[size] = null; // Eliminate obsolete reference
return result;
}
public void popAll(Collection<List<? super E>> dst) {
while (!isEmpty()) {
dst.add(pop());
}
}
}
// Not working: `Collection<List<? super ValidationError>` can not be applied to Collection<List<ServerError>>
public void test() {
YetAnotherStack<ValidationError> stack = new YetAnotherStack<>();
Collection<List<ServiceError>> errors =
Arrays.asList(List.of(new ValidationError("A")), List.of(new ValidationError("B")));
stack.popAll(errors);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment