我需要根据名称对列表进行排序,但我可以做到。
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaexception;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
/**
*
* @author Admin
*/
class person
{
int id;
String name;
};
public class JavaException
{
public static void main(String a[])
{
List<person> li =new ArrayList<person>();
person p=new person();
p.id=1;
p.name="Sushant";
li.add(p);
person p1=new person();
p1.id=2;
p1.name="Atul";
li.add(p1);
person p2=new person();
p2.id=3;
p2.name="Genu";
li.add(p2);
System.out.println(""+li);
Collections.sort(li);
for(int i=0;i<li.size();i++)
{
person pp=(person)li.get(i);
System.out.println(""+pp.name);
}
}
}
它给了我一个错误
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: java.util.Collections.sort
[javaexception.person@14b7453, javaexception.person@c21495, javaexception.person@1d5550d]
at javaexception.JavaException.main(JavaException.java:41)
最佳答案
使用 Collections.sort(List<T> list)
时, 编译器要求类型 T 必须是可比较的 ( <T extends Comparable<? super T>>
)。
您的 Person
不是这种情况类(class)。要么制作 Person
类是可比较的(通过实现 Comparable
接口(interface)),或者使用重载的 sort
提供自定义比较器方法。
关于java - 需要在java中根据名称排序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27330249/