在Java中实现Clone还有其他选择吗? [英] Are there any alternatives to implementing Clone in Java?

查看:175
本文介绍了在Java中实现Clone还有其他选择吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Java项目中,我有一个各种类型的交易者的向量。这些不同类型的交易者是Trader类的子类。现在,我有一个方法,以Trader作为参数,并在向量中存储50次左右。我遇到了问题,因为存储相同的对象50次只是存储同一对象的50个引用。我需要存储50个副本的对象。我已经研究过如何实现克隆,但我不希望程序员定义一种交易者必须担心让他们的类可克隆。此外,正如此页所述,实施克隆会创建各种类型问题。我认为复制构造函数不会起作用,因为如果我在Trader类中定义了一个,它就不会知道它正在复制的Trader的类型,只是制作一个通用的Trader。我该怎么办?

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?

编辑:我真的不想制作某个特定对象的精确副本。我真正想要做的是在向量中添加一定数量的交易者。问题是用户需要在参数中指定他想要添加的交易者类型。这是我想要做的一个例子:(虽然我的语法完全是虚构的)

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*())
}

如何在Java中实现这样的目标?

How can I achieve something like this in Java?

推荐答案

只需添加抽象复制方法即可。您可以使用协变返回类型,以便指定派生类型以返回派生实例,这可能重要也可能不重要。

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);
    }
    ...
}

有时你可能想要通常处理需要克隆然后返回正确类型集合的派生类型 Trader 的集合。为此,您可以以惯用的方式使用泛型:

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);
    }
    ...
}

这篇关于在Java中实现Clone还有其他选择吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆