数组有工具类Arrays,集合也有一个工具类Collections。
sort方法:
sort(List list):根据其元素natural ordering对制定的列表进行排序
sort(List list, Comparator super T> c):根据指定的比较器引起的顺序对指定的列表进行排序
案例:
package com.gongxy.demo;
public class Persion implements Comparable{
private String no;
private String name;
private int age;
private double socre;
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSocre() {
return socre;
}
public void setSocre(double socre) {
this.socre = socre;
}
@Override
public String toString() {
return "Persion{" +
"no='" + no + ''' +
", name='" + name + ''' +
", age=" + age +
", socre=" + socre +
'}';
}
@Override
public int compareTo(Persion o) {
//return this.age - o.age;//按照年龄升序
return o.age - this.age;//按照年龄降序
}
}
package com.gongxy.demo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ListSortTest {
public static void main(String[] args) {
//comparableTest();
comparatorTest();
}
static void comparableTest(){
List list = createPersonList();
Collections.sort(list);
System.out.println(list);
//[Persion{no='3', name='gongxh', age=1, socre=62.5}, Persion{no='3', name='gongxy', age=3, socre=68.5}, Persion{no='1', name='gongyg', age=29, socre=98.5}, Persion{no='2', name='gumd', age=31, socre=95.2}]
}
static void comparatorTest(){
List list = createPersonList();
Collections.sort(list, new ComparatorDemo());
System.out.println(list);
}
static List createPersonList(){
List list = new ArrayList();
Persion p = new Persion();
p.setNo("1");
p.setName("gongyg");
p.setAge(29);
p.setSocre(98.5);
list.add(p);
p = new Persion();
p.setNo("2");
p.setName("gumd");
p.setAge(31);
p.setSocre(95.2);
list.add(p);
p = new Persion();
p.setNo("3");
p.setName("gongxy");
p.setAge(3);
p.setSocre(68.5);
list.add(p);
p = new Persion();
p.setNo("3");
p.setName("gongxh");
p.setAge(1);
p.setSocre(62.5);
list.add(p);
return list;
}
}
class ComparatorDemo implements Comparator {
@Override
public int compare(Persion o1, Persion o2) {
return (int)(o1.getSocre() - o2.getSocre());
}