Comparator won't work with Arrays.sort

前端 未结 5 1211
迷失自我
迷失自我 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:11

    As the error message suggest the problem is actually caused by the list being passed instead where an array is expected, nothing to do with the comparator.

    Try the following instead

    Arrays.sort(elist.toArray(), new CalorieComparator());
    

    But with that you will not get the desired result ultimately, because it will sort the brand new array just created instead of the list itself. But that you should get the idea of what the error message was trying to say. Just make sure not to pass a list there, it's meant to sort an array and not a list.

    As others have suggested please use the Collections.sort method instead to get the desired result.

    Also, just a side note, you should extend the generic version Comparator instead of the non-generic one.

提交回复
热议问题