JAVA 实现了comparable也写了compareTo为什么还是没排序?
代码是这样的,想按age排序,但是输出的还是没排序的age,不知道哪里错了~importjava.util.LinkedList;publicclassMyLinked{...
代码是这样的,想按age排序,但是输出的还是没排序的age,不知道哪里错了~
import java.util.LinkedList;
public class MyLinked
{
public static void main(String[] args)
{
LinkedList<Info2> list = new LinkedList<Info2>();
list.add(new Info2("Aaron",23));
list.add(new Info2("POPO",19));
list.add(new Info2("Milk",21));
System.out.println(list.get(0).getAge());
System.out.println(list.get(1).getAge());
System.out.println(list.get(2).getAge());
}
}
class Info2 implements Comparable<Object>
{
private String name;
private int age;
Info2(String name,int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return this.name;
}
public int getAge()
{
return this.age;
}
@Override
public int compareTo(Object o) {
return age - ((Info2)o).getAge();
}
} 展开
import java.util.LinkedList;
public class MyLinked
{
public static void main(String[] args)
{
LinkedList<Info2> list = new LinkedList<Info2>();
list.add(new Info2("Aaron",23));
list.add(new Info2("POPO",19));
list.add(new Info2("Milk",21));
System.out.println(list.get(0).getAge());
System.out.println(list.get(1).getAge());
System.out.println(list.get(2).getAge());
}
}
class Info2 implements Comparable<Object>
{
private String name;
private int age;
Info2(String name,int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return this.name;
}
public int getAge()
{
return this.age;
}
@Override
public int compareTo(Object o) {
return age - ((Info2)o).getAge();
}
} 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询