数组对象"复制"

时间:2016-04-01 16:45:26

标签: java arrays duplicates

我正在用java创建游戏。我正在使用一系列装甲装备 问题是,每当我更改数组中的1个变量时,其他对象也会受到影响。这看起来像一个指针问题但是,所有对象都已初始化为单独的并被称为new。

private Armor[] equip = new Armor[3];
public Inventory()
{
    for(int i = 0; i<3;i++)
        equip[i] = new Armor();

    equip[0] = new Armor("head","You don't have head equipment","head",0,10,0,0);
    equip[1] = new Armor("tunic","A simple farmers tunic","chest",0,10,0,0);
    equip[2] = new Armor("baggy pants","Basic pants woven from rough cloth","legs",0,10,0,0);


    System.out.println(armorDes(0));
    System.out.println(armorDes(1));
    System.out.println(armorDes(2));
}

所有打印行输出

baggy pants
0 armor
10 evasion bonus
Basic pants woven from rough cloth

而不是他们自己的统计数据。

使用调试器对其进行了测试,并将所有对象声明到数据中的不同位置。这是一个java问题,我只是愚蠢吗?

1 个答案:

答案 0 :(得分:0)

上面的代码不清楚

private Armor[] equip = new Armor[3];
public Inventory()
{
for(int i = 0; i<3;i++)
    equip[i] = new Armor();// Why creating object using default constructor here? no use

equip[0] = new Armor("head","You don't have head equipment","head",0,10,0,0);
equip[1] = new Armor("tunic","A simple farmers tunic","chest",0,10,0,0);
equip[2] = new Armor("baggy pants","Basic pants woven from rough cloth","legs",0,10,0,0);

// Use toString() method in Armour class to see the values present in variables. 
//Also be sure all variables are instance variables 

System.out.println(equip[0]);
System.out.println(equip[1]);
System.out.println(equip[2]);

//System.out.println(armorDes(0));
//System.out.println(armorDes(1));
//System.out.println(armorDes(2));

}