Sorting two arrays simultaneously

后端 未结 8 2151
终归单人心
终归单人心 2020-12-01 17:29

I\'m learning and understanding Java now, and while practising with arrays I had a doubt. I wrote the following code as an example:



        
8条回答
  •  孤城傲影
    2020-12-01 18:06

    You should not have two parallel arrays. Instead, you should have a single array of WestWingCharacter objects, where each object would have a field name and a field number.

    Sorting this array by number of by name would then be a piece of cake:

    Collections.sort(characters, new Comparator() {
        @Override
        public int compare(WestWingCharacter c1, WestWingCharacter c2) {
            return c1.getName().compareTo(c2.getName();
        }
    });
    

    or, with Java 8:

    Collections.sort(characters, Comparator.comparing(WestWingCharacter::getName));
    

    Java is an OO language, and you should thus use objects.

提交回复
热议问题