Comparator won't work with Arrays.sort

前端 未结 5 1213
迷失自我
迷失自我 2021-01-21 07:03

So I\'m working on a comparator problem and I can\'t figure out why the Array.sort in this first class is giving me the error of:

The method

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-21 07:24

    Ignoring your actual problem with Arrays.sort vs. Collections.sort (that has been beautifully answered), it might be a good idea to implement a Comparator instead of casting your Objects in the compare method:

    public class CalorieComparator implements Comparator {
    
      @Override
      public int compare(Edible o1, Edible o2) {        
        if (o1.getCalories() > o2.getCalories()) {
            return 1;
        } else if (o1.getCalories() < o2.getCalories()) {
            return -1;
        } else {
            return 0;
        }
      }
    }
    

提交回复
热议问题