I want to write a generic class that is a First-in-First-out queue with the basic Push and Pop operations, here is the class:
class queue<E>
{
protected final class elem
{
public E val;
public elem next=null;
public elem(){}
public elem(E v)
{
val=v;
}
}
protected elem head=null,tail=null;
public queue()
{
}
public queue(E v)
{
head=new elem(v);
}
public void push(E v)
{
if(head==null)
head=tail=new elem(v);
else if(head==tail)
{
tail=new elem(v);
head.next=tail;
}
else
{
elem t=new elem(v);
tail.next=t;
tail=t;
t=null;
}
}
public final E peek()
{
return ((tail!=null)?tail.val:null);
}
public E pop()
{
if(head==null)
return null;
E i=head.val;
if(head!=tail)
head=head.next;
else
head=tail=null;
return i;
}
}
The problem is in the elem constructor here:
public elem(E v)
{
val=v;
}
I don't want to assign v to val but I want to clone it(shallow copy).
here the things I tried:
1- the clone method: well because it's protected in Object class, I can't access it from an E variable.
2- queue<E extends Cloneable>
: didn't solve the problem, actually Cloneable is an empty interface, it doesn't add any methods.
3- using the priorityqueue: that may be easier than writing a queue class on your own but I don't want priority, just Fifo structure.
4- implementing the queue interface: in which you must implement many methods that most of them I don't need, also I still have to clone by myself.
So, what to try next ?