Created
June 18, 2023 11:01
-
-
Save romanbsd/65455fe6dc01ca216a4488f46d563fd1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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