سؤال

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 ?

هل كانت مفيدة؟

المحلول

You can create interface CustomCloneable:

interface CustomCloneable {
    public CustomCloneable clone();
}

And use it in your situation. Note that you will have to provide clone implementation for your classes or use methods/libraries described below.

class Queue<E extends CustomCloneable>

And after that you can call clone method on your

public Elem(E v) {
    val = (E) v.clone();
}

On the other hand you might be looking for sth else. Refer here for other options and why you should avoid cloning.

Instead of that use some other options, like apache-commons [SerializationUtils][1] (deep-clone) or BeanUtils (shallow-clone), or simply use a copy-constructor.

Also please read java code conventions

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top