Java 如何将同一对象添加到多态数组中,但能够对该对象的重复版本进行更改?

Java 如何将同一对象添加到多态数组中,但能够对该对象的重复版本进行更改?,java,android,arrays,Java,Android,Arrays,所以我有一个多态数组列表类型卡 private ArrayList<Card> compSciDeck = new ArrayList<Card>(); 然后使用for循环将这些卡随机添加到ArrayList中。(在此for循环之前还添加了一张卡) for(int i=0;i您必须先克隆卡对象,然后再将其添加到compscidack集合中 大致如下: for (int i = 0; i <= 4; i++) { Random rand = new Rand

所以我有一个多态数组列表类型卡

private ArrayList<Card> compSciDeck = new ArrayList<Card>();
然后使用for循环将这些卡随机添加到ArrayList中。(在此for循环之前还添加了一张卡)


for(int i=0;i您必须先克隆
对象,然后再将其添加到
compscidack
集合中

大致如下:

for (int i = 0; i <= 4; i++) {
    Random rand = new Random();
    int index = rand.nextInt(3);
    compSciDeck.add(i+1, compSciSpell[index].clone());
}
使用复制构造函数,您可以将代码重新写入:

for (int i = 0; i <= 4; i++) {
    Random rand = new Random();
    int index = rand.nextInt(3);
    compSciDeck.add(i+1, new SpellCard((SpellCard) compSciSpell[index]));
}

for(int i=0;i)java中的对象是可变的,您正在加入一个引用。如果您修改一个,另一个也会更改。由于我有一个继承层次结构,我将如何执行此操作?我会得到错误“没有可用的默认构造函数”您可以将一个默认构造函数与现有构造函数一起添加
for (int i = 0; i <= 4; i++) {
    Random rand = new Random();
    int index = rand.nextInt(3);
    compSciDeck.add(i+1, compSciSpell[index].clone());
}
public static class SpellCard {

    private int index;

    private String name;

    ... // more fields here

    public SpellCard(int index, String name) {
        this.index = index;
        this.name = name;
        ... // more fields here.
    }

    // Copy constructor
    public SpellCard(SpellCard other) {
        this.index = other.index;
        this.name = other.name;
        ... // more fields here
    }
}
for (int i = 0; i <= 4; i++) {
    Random rand = new Random();
    int index = rand.nextInt(3);
    compSciDeck.add(i+1, new SpellCard((SpellCard) compSciSpell[index]));
}