我试图将Users的ArrayList转换为Comparable的ArrayList,Users类实现Comparable,但这似乎是不可能的。这是我为测试此功能而编写的代码:
public static void main(String[] args) {
ArrayList<User> users = new ArrayList<User>();
users.add(new User("Tom", "Jefferson",2));
users.add(new User("White", "Walt", 29));
System.out.println(getGreatest(users));
}
//return the greatest item in the array list
public static Comparable getGreatest(ArrayList<Comparable> arrayList){
Comparable greatest = arrayList.get(0);
for(Comparable c : arrayList){
if (c.compareTo(greatest) > 0){
greatest = c;
}
}
return greatest;
}
当然,User类实现Comparable接口,并具有compareTo方法。
class User implements Comparable<User>{
...
}
当我尝试编译代码时,出现以下错误:
Error:(11, 40) java: incompatible types: java.util.ArrayList<com.company.User> cannot be converted to java.util.ArrayList<java.lang.Comparable>
我做错了还是Java不支持此操作?有解决此问题的解决方法吗?