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
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<T>
instead of the non-generic one.
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<Edible>
instead of casting your Objects in the compare method:
public class CalorieComparator implements Comparator<Edible> {
@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;
}
}
}
Arrays.sort
takes an array as its first argument. To sort a collection such as a list, use Collections.sort
.
Collection.sort(elist, new CalorieComparator());
Also, note that your method won't compile because you aren't returning a List<Edible>
.
An ArrayList
is different from a Java array; since you're using a List, Arrays.sort
won't help you here.
Consider Collections.sort instead.
Arrays.sort(elist, new CalorieComparator());
You are calling a sort()
of Arrays
class with ArrayList
, ArrayList
belongs to Collection
family not an Array
.
your error will resolved if you use Collectinss.sort()