I'm confused as to what I am doing wrong with this implementation of AbstractQueue.
This code is what is causing the error:
public static void main(String[] args) {
Stack<Integer> intStack = new Stack();
MyQueue<Integer> realQueue = new MyQueue();
PriorityQueue<Integer> intQueue = new PriorityQueue();
}
Eclipse is saying I need to remove the generic typing from MyQueue.
Here is the class as implemented:
import java.util.AbstractQueue;
import java.util.Iterator;
public class MyQueue extends AbstractQueue<Object> {
private T[] arr;
private int headPos;
private int tailPos;
private int size = 0;
@Override
public boolean offer(T e) {
if (size < arr.length)
size++;
else if (headPos == tailPos)
headPos = nextPos(headPos);
arr[tailPos] = e;
tailPos = nextPos(tailPos);
return true;
}
private int nextPos(int pos) {
return (pos + 1) % arr.length;
}
@Override
public T peek() {
if (size == 0)
return null;
return arr[headPos];
}
@Override
public T poll() {
if (size == 0)
return null;
size--;
T res = arr[headPos];
headPos = nextPos(headPos);
return res;
}
@Override
public Iterator iterator() {
// TODO Auto-generated method stub
return null;
}
@Override
public int size() {
return size;
}
}
This is both my first time implementing a queue, and my first time creating a class to work with generics, so I am thoroughly lost as to what to do. When I follow Eclipse's advice, I get a null pointer exception, and when I leave the generic code in, it does not compile.
public class MyQueue<T> extends AbstractQueue<T>.ObjectwithTpublic class MyQueue<T> extends AbstractQueue<T>. Your variable declarations need to specify the generic parameter type on the RHS -Stack<Integer> intStack = new Stack<Integer>();. And your NPE is coming from somewhere else in your code.