Java:我的新对象实例化正在更改先前的对象引用



我正试图弄清楚这里发生了什么,并将感谢任何帮助。我有一个循环,我创建新对象,然后将它们添加到数组列表中。但似乎每次通过循环,新对象实际上也在改变先前创建的对象。我理解ArrayList实际上只包含对对象的引用,但我认为通过每次调用new,我将创建新的实例,因此每个引用都是唯一的。

代码如下:

void copyFields()
{
    String fruitStr = "apple red,banana yellow,orange orange,pear green,grape purple";
    String[][] fruitArray = new String[5][];
    String[] fruitPairs = fruitStr.split(",");
    int r = 0;
    for (String fruitPair : fruitPairs) 
    {
        fruitArray[r++] = fruitPair.split(" ");
    }
    ArrayList<Fruit> fruitList = new ArrayList<Fruit>();
    for (String[] f : fruitArray)
    {
        Fruit fruitObj = new Fruit(f[0],f[1]);
        fruitList.add(fruitObj);
    }
}

所以在结束时,fruitList包含5个对象-都与fruitArray中的最后一个元素(葡萄紫色)相同。

你可以看到,我正在尝试从一个包含水果/颜色对列表的字符串,到一个二维数组,再到一个水果对象的数组列表。我可以验证每一步都是正确工作的,直到我在调试器中观察到,每次通过for循环都会改变水果列表中所有先前的对象。

我在这里错过了什么?

我已经测试了你的代码,它与经典的Fruit实现:

public class Fruit {
    private String name;
    private String color;
    public Fruit(String name, String color) {
        this.color = color;
        this.name = name;
    }
}

所以我假设字段是static:

public class Fruit {
    private static String name;
    private static String color;
    public Fruit(String name, String color) {
        Fruit.color = color;
        Fruit.name = name;
    }
}

如果你不需要你的中间fruitArray在你的应用程序的其他地方,你可以简化你的代码如下:

String pairsStr = "apple red,banana yellow,orange orange,pear green,grape purple";
ArrayList<Fruit> fruits = new ArrayList<Fruit>();
String[] pairs = pairsStr.split(",");
for (String pairStr : pairs) {
    String[] pair = pairStr.split(" ");
    fruits.add(new Fruit(pair[0], pair[1]));
}

我创建了以下示例,并使用compileonline对其进行了测试,没有出现任何问题。问题可能是在你的Fruid类:

import java.util.ArrayList;
public class HelloWorld{
    public static void main(String []args){
        String fruitStr = "apple red,banana yellow,orange orange,pear green,grape purple";
        String[][] fruitArray = new String[5][];
        String[] fruitPairs = fruitStr.split(",");
        int r = 0;
        for (String fruitPair : fruitPairs) 
        {
            fruitArray[r++] = fruitPair.split(" ");
        }
        ArrayList<String> testList = new ArrayList<String>();
        for (String[] f : fruitArray)
        { 
            String testString = f[0] + " + " + f[1];
            System.out.println(testString);
            testList.add(testString);
        }
        for (String s: testList) {
            System.out.println(s);
        }
     }
} 
结果:

apple + red
banana + yellow
orange + orange
pear + green
grape + purple
apple + red
banana + yellow
orange + orange
pear + green
grape + purple

最新更新