首页 > 基础教程 > 集合框架 > LinkedList类
Java LinkedList排序
LinkedList通过Collections.sort进行排序,代码如下:
降序
public class Person1 implements Comparable < Person1 > {
private Float height;
private String name;
Person1(float height) {
this.height = height;
}
public Float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override public int compareTo(Person1 p) {
if (this.getHeight() < p.getHeight()) {
return 1;
} else if (this.getHeight() > p.getHeight()) {
return - 1;
} else {
return 0;
}
}
}
public class Question3_1 {
public static void main(String[] args) {
Person1 p1 = new Person1(23.4f);
p1.setName("Stud1");
Person1 p2 = new Person1(2.34f);
p2.setName("Stud2");
Person1 p3 = new Person1(34.32f);
p3.setName("Stud3");
Person1 p4 = new Person1(56.45f);
p4.setName("Stud4");
Person1 p5 = new Person1(21.4f);
p5.setName("Stud5");
LinkedList < Person1 > al = new LinkedList < Person1 > ();
al.add(p1);
al.add(p2);
al.add(p3);
al.add(p4);
al.add(p5);
Collections.sort(al); //这里控制降序
for (Person1 p: al) System.out.println(p.getName() + " " + p.getHeight());
}
}
运行结果:
Stud4 56.45
Stud3 34.32
Stud1 23.4
Stud5 21.4
Stud2 2.34
升序
修改上面代码 Collections.sort(al,Collections.reverseOrder());//更改为升序
运行结果:
Stud2 2.34
Stud5 21.4
Stud1 23.4
Stud3 34.32
Stud4 56.45
版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。