Skip to content

Instantly share code, notes, and snippets.

@romanbsd
Created June 18, 2023 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romanbsd/65455fe6dc01ca216a4488f46d563fd1 to your computer and use it in GitHub Desktop.
Save romanbsd/65455fe6dc01ca216a4488f46d563fd1 to your computer and use it in GitHub Desktop.
import java.util.AbstractList;
import java.util.Deque;
import java.util.LinkedList;
public class DequeList<T> extends AbstractList<T> {
private final Deque<T> deque;
public DequeList(Deque<T> deque) {
this.deque = deque;
}
@Override
public T get(int index) {
if (index < 0 || index >= size()) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size());
}
return deque.toArray(new Object[0])[index];
}
@Override
public int size() {
return deque.size();
}
@Override
public boolean add(T element) {
deque.addLast(element);
return true;
}
@Override
public void add(int index, T element) {
if (index < 0 || index > size()) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size());
}
if (index == 0) {
deque.addFirst(element);
}
else if (index == size()) {
deque.addLast(element);
} else {
throw new UnsupportedOperationException("Insertion at index is not supported.");
}
}
@Override
public T remove(int index) {
if (index < 0 || index >= size()) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size());
}
if (index == 0) {
return deque.removeFirst();
} else if (index == size() - 1) {
return deque.removeLast();
}
throw new UnsupportedOperationException("Removal at index is not supported.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment