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 sort(T[], Comparator) in the type Arrays is not applicable for the arguments (ArrayList, CalorieComparator)
Restaurant Class:
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public class Restaurant {
private ArrayList<Edible> elist;
public Restaurant() {
}
public void addEdibleItem(Edible item){
elist.add(item);
}
public List<Edible> orderByCalories(){
Arrays.sort(elist, new CalorieComparator());
}
CalorieComparator class:
import java.util.Comparator;
public class CalorieComparator implements Comparator {
public int compare(Object o1, Object o2){
Edible thisfood = (Edible)o1;
Edible otherfood = (Edible)o2;
if(thisfood.getCalories() > otherfood.getCalories())
return 1;
else if (thisfood.getCalories() < otherfood.getCalories())
return -1;
else
return 0;
}
}
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.
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>
.
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.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.