我想我的代码是自我解释的。

public Town[] GetShortestDistanceBetweenTowns() {
    Town[] allTowns = getTowns();
    Town[] bestPath = allTowns;
    int bestDistance = CalculateDistance(bestPath);
    int newDistance = bestDistance;

    //shuffle allTowns array and look for best distance
    for(int i=0; i<100; i++) {
        MixArray(allTowns);
        newDistance = CalculateDistance(allTowns);

        if (newDistance < bestDistance) {
            bestPath = allTowns;
            bestDistance = newDistance;
        }
    }

    return bestPath;
}

问题是当我使用MixArray(allTowns)时,它也在改变我的bestPath数组的顺序。我只想在这个数组中保持最好的顺序我该怎么办?

最佳答案

Town是引用类型,因此Town[] bestPath = allTowns;意味着bestPath将始终匹配allTowns。要复制,您可以为Town类实现iclonable,或者只需添加一个copy函数,该函数创建一个具有重复值的新Town
这里有一篇关于参考与价值类型的好文章:
http://www.albahari.com/valuevsreftypes.aspx

08-24 13:06