跟踪数组元素顺序



我认为我的代码是不言自明的。

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,或者只需添加一个复制函数,该函数使用重复的值创建新Town

这是一篇关于引用与值类型的精彩文章:http://www.albahari.com/valuevsreftypes.aspx

最新更新