Java Collections.sort Comparator修改私有对象ID?

时间:2015-04-05 16:12:32

标签: java sorting collections

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

我正在使用Player对象中的自定义Comparator对此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字段是&#39; munged&#39;并与其他已排序的对象一致地设置。

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这样的事情,但排序似乎是以某种方式这样做。

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

1 个答案:

答案 0 :(得分:3)

  

在构造期间,它们的私有id已设置,并且只能通过getId()方法访问。 Continent对象没有setId()等。

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

相关问题