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
ArrayListis different from a Java array; since you’re using a List,Arrays.sortwon’t help you here.Consider
Collections.sortinstead.