Search code examples
javareferencevectorclonesubclass

Are there any alternatives to implementing Clone in Java?


In my Java project, I have a vector of various types of Traders. These different types of traders are subclasses of the Trader class. Right now, I have a method that takes a Trader as an argument and stores it 50 or so times in the vector. I am having problems because storing the same object 50 times is just storing 50 references of the same object. I need to store 50 copies of the object. I've researched about implementing Clone, but I don't want the programmers defining a type of Trader to have to worry about making their class cloneable. Also, as pointed out by this page, implementing clone creates all sorts of problems. I don't think a copy constructor would work either because if I defined one in the Trader class, it would not know the type of Trader it was copying and just make a generic Trader. What can I do?

Edit: I am not really wanting to make exact copies of a certain object. What I am really trying to do is to add a certain number of Traders to the vector. The problem is that the user needs to specify in an argument which type of Trader he wants to add. Here is an example of what I am trying to do: (although my syntax is completely imaginary)

public void addTraders(*traderType*)
{
    tradervect.add(new *traderType*())
}

How can I achieve something like this in Java?


Solution

  • Just add an abstract copy method. You can use covariant return types so that the derived type is specified to return a derived instance, which may or may not be important.

    public interface Trader {
        Trader copyTrader();
        ...
    }
    
    
    public final class MyTrader implements Trader {
        MyTrader copyTrader() {
            return new MyTrader(this);
        }
        ...
    }
    

    Sometimes you might want to generically deal with a collection of derived type of Trader that needs to clone and then return the a properly typed collection. For that you can use generics in an idiomatic way:

    public interface Trader<THIS extends Trader> {
        THIS copyTrader();
        ...
    }
    
    
    public final class MyTrader implements Trader<MyTrader> {
        public MyTrader copyTrader() {
            return new MyTrader(this);
        }
        ...
    }