Sorting Parallel Arrays in Java

后端 未结 5 625
青春惊慌失措
青春惊慌失措 2021-01-21 06:19

I have two arrays, one stores the distance of the cities and the other stores the corresponding population. Everything works fine if the distance of the cities is in ascending o

5条回答
  •  逝去的感伤
    2021-01-21 07:07

    The good way of doing this is having a city class:

    class City{
        private int id;
        private long population;
    
        //... getters, setters, etc
    }
    

    a city comparator class:

    class CityPopulationComparator implements Comparator {
        @Override
        public int compare(City c1, City c2) {
            return Long.compare(c1.getPopulation(), c2.getPopulation());
        }
    }
    

    And an array list of cities:

    ArrayList cities;
    

    and finally sort it using:

    Collections.sort(cities, new CityPopulationComparator());
    

    But if you need to have your cities and populations this way, you can write a sort method yourself (a bubble sort for example) and whenever you swap two cities, also swap corresponding pupulations.

提交回复
热议问题