Java Collections.sort 比较器修改私有对象ID?

Java Collections.sort Comparator modifies private object ID?

我知道这是一个有点奇怪的问题。我有一个构造的 Continent 对象的 ArrayList。在构造期间,它们的私有 ID 已设置,并且只能通过 getId() 方法访问。 Continent 对象没有 setId() 等。

我正在使用来自 Player 对象的自定义比较器对这个 ArrayList 进行排序。

private ArrayList<Continent> sortContinentsByOwnership(ArrayList<Continent> continents)
{
    Collections.sort(continents, new Comparator<Continent>(){
        @Override
        public int compare(Continent a, Continent b)
        {
            Float a_unowned_percentage = a.getUnownedPercentage();
            Float b_unowned_percentage = b.getUnownedPercentage();
            return a_unowned_percentage.compareTo(b_unowned_percentage);
        }
    });
    return continents;
}

这在排序对象时效果很好。但是,通过以下代码使用此方法后,大陆的 id 字段为 'munged' 并与其他排序对象设置一致。

contested_continents = this.sortContinentsByOwnership(contested_continents);

我已确保对象已正确排序,但这里有一些示例输出在排序尝试前后访问大陆的 ID 属性。排序后大陆的 id 反映了从中调用排序的对象的 id 字段,在本例中是 Player 对象。

Continents Pre-Sort - 0 2 6 7 8 
Continents Post-Sort - 5 5 5 5 5 

Continents Pre-Sort - 1 2 10 
Continents Post-Sort - 0 0 0

Continents Pre-Sort - 0 4 6 11 
Continents Post-Sort - 1 1 1 1

访问这些对象的其他属性,发现在id属性之外仍然是具有相同元素的相同对象。

在代码的任何地方,无论是排序还是其他,我都在做类似 continent.id = player.id 的事情,但排序似乎以某种方式在做这个。

欢迎提出任何建议或建议,如有必要,我很乐意提供其他资源。谢谢。

During construction, their private id is set, and only accessible through a getId() method. There is no setId() or the like for the Continent object.

由于您不打算修改 id 字段,我建议将其声明为 final。这将保证它不会在构造函数之外更改,并且更容易发现它现在正在更改的位置。