Queue implementation: generics
Hi all!
I've written a small AbstractQueue subclass for caching discardable
values.
Policy: It is fixed in size, add/offer *always* works, the peek and
poll methods always return the first element (can be null), so remove
and element will throw an exception in the null case.
My current implementation is:
public class FixedSizeShiftQueue<E> extends AbstractQueue
{
private final Object[] elems;
//private final E[] elems;
public FixedSizeShiftQueue(int size)
{
if ( size < 1 )
{
throw new IllegalArgumentException("Size is smaller than 1!");
}
this.elems = new Object[size];
//this.elems = new E[size]; //ERROR: Cannot create a generic array
of E
}
public int size()
{
return elems.length;
}
//@Override
public boolean offer(Object obj)
{
//shift left all by 1
for ( int i = 0; i < elems.length - 1 ; i++ )
{
//copy
elems[i] = elems[i + 1];
}
elems[elems.length - 1] = obj;
//elems[elems.length - 1] = (E)obj; //WARNING: Type safety: The cast
from Object to E is actually checking against the erased type Object
return true;
}
public E poll()
{
return (E)elems[0]; //Type safety: The cast from Object to E is
actually checking against the erased type Object
}
public E peek()
{
return (E)elems[0]; //Type safety: The cast from Object to E is
actually checking against the erased type Object
}
public Iterator iterator()
{
ArrayList al = new ArrayList();
for ( Object elem : elems )
{
al.add(elem); //WARNING: Type safety: The method add(Object)
belongs to the raw type ArrayList. References to generic type
ArrayList<E> should be parameterized
}
return al.iterator();
}
}
In the lines with the comments, I get the warnings behind the "//".
In the alternative implementation (outcommented!) I tried to go with
an E[], but it is even worse (uncompilable).
Can anybody explain how to correct this implementation so no warnings
appear? I might need to implement more queues, so this kind of
"homework" :-/ has to be done first.
I looked at the JDK sources of AbstractQueue, AbstractCollection and
mainly Vector, but I couldn't get it done.
TIA
Karsten
PS: Please note this will never be the final implementation