用Java排序并行数组

Nik*_*rma 3 java arrays

我有两个数组,一个存储城市的距离,另一个存储相应的人口.如果城市的距离按升序排列,一切正常.但是,如果有人随机输入距离.如何对城市数组进行排序,并确保相应城市的人口与其各自城市人口的指数处于同一指数中.

例如:

  • 城市1的人口333
  • 城市3的人口为33333
  • 城市5有33人口

int[] city = {1, 3, 5};
int[] pop  = {333, 33333, 33};
Run Code Online (Sandbox Code Playgroud)

一切正常,因为城市数组已经排序.

但是当我输入时:

    int[] city = {3, 1, 5}; 
    int[] pop  = {3333, 333, 33};
Run Code Online (Sandbox Code Playgroud)

大问题!

我想对数组城市进行排序,并确保种群数组的所有元素与其各自的城市具有相同的索引.

Ali*_*edi 8

这样做的好方法是拥有一个城市类:

class City{
    private int id;
    private long population;

    //... getters, setters, etc
}
Run Code Online (Sandbox Code Playgroud)

城市比较班:

class CityPopulationComparator implements Comparator<City> {
    @Override
    public int compare(City c1, City c2) {
        return Long.compare(c1.getPopulation(), c2.getPopulation());
    }
}
Run Code Online (Sandbox Code Playgroud)

以及城市的数组列表:

ArrayList<City> cities;
Run Code Online (Sandbox Code Playgroud)

最后使用:

Collections.sort(cities, new CityPopulationComparator());
Run Code Online (Sandbox Code Playgroud)

但是如果你需要以这种方式拥有你的城市和人口,你可以自己编写排序方法(例如泡泡排序),每当你交换两个城市时,也要交换相应的瞳孔.

  • @ Mr.Polywhirl有很多方法可以对城市进行分类.我不确定按人口排序比按id排序更自然.这使得使用比较器进行特定排序是一个很好的计划.我本来称之为CityPopulationComparator. (2认同)