Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Oblig1_nid005;
- import java.util.Arrays;
- public class ArrayDeque<E> implements IDeque<E> {
- private int capacity;
- private E[] array;
- private int size;
- private int first;
- private int last;
- @SuppressWarnings("unchecked")
- public ArrayDeque(int capacity) {
- this.array = (E[]) new Object[capacity];
- this.capacity = capacity;
- size = 0;
- }
- /**
- * privat metode som sjekker om arrayet er fullt.
- * @return true dersom arrayet er fullt og false hvis ikke.
- */
- private boolean fullArray() {
- if (size == capacity) {
- return true;
- } else {
- return false;
- }
- }
- /**
- * privat metode som sjekker om arrayet er tom.
- * @return true dersom arrayet er tomt og false hvis ikke.
- */
- private boolean emptyArray() {
- if (size == 0) {
- return true;
- } else {
- return false;
- }
- }
- public int size() {
- return size;
- }
- public void addFirst(E elem) throws DequeFullException {
- if (fullArray()) {
- throw new DequeFullException("Array is full");
- } array[first] = elem;
- first = (first + 1) % (capacity);
- size++;
- }
- public E pullFirst() throws DequeEmptyException {
- if(emptyArray()) {
- throw new DequeEmptyException("Array is empty");
- }if(first == 0) {
- first = capacity;
- first = (first - 1) % (capacity);
- size--;
- }
- return array[first];
- }
- public E peekFirst() throws DequeEmptyException {
- if (emptyArray()){
- throw new DequeEmptyException("Array is empty");
- } else {
- return array[0];
- }
- }
- public void addLast(E elem) throws DequeFullException {
- if (fullArray()){
- throw new DequeFullException("Array is full");
- } array[last] = elem;
- last = (last - 1) % (capacity);
- size++;
- }
- public E pullLast() throws DequeEmptyException {
- if (emptyArray()) {
- throw new DequeEmptyException("Array is empty");
- } else {
- last = (last + 1) % (capacity);
- size--;
- return array[last];
- }
- }
- public E peekLast() throws DequeEmptyException{
- if (emptyArray()) {
- throw new DequeEmptyException("Array is empty");
- } else {
- return array[(last + 1) % capacity];
- }
- }
- /**
- * Metode som fjerner elementer i arrayet, blir brukt av clear().
- * @return resultate etter fjerningen.
- */
- private E remove(){
- E result = null;
- if (size > 0){
- result = array[size - 1];
- array[size - 1] = null;
- size--;
- }return result;
- }
- public void clear() {
- while (!emptyArray()){
- remove();
- }
- }
- public boolean contains(Object elem){
- boolean found = false;
- int index = 0;
- while (!found && (index <= array.length)) {
- if (elem.equals(array[index])){
- found = true;
- }
- index++;
- }
- return found;
- }
- @SuppressWarnings("unchecked")
- public <T> T[] toArray(T[] a) {
- return (T[]) Arrays.copyOf(array, array.length, a.getClass());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement