java_Collections集合工具类的方法_sort(List)
Collections集合工具类的方法_sort(List)
两个对象比较的结果有三种:大于,等于,小于。
如果要按照升序排序,
则o1 小于o2,返回(负数),相等返回0,01大于02返回(正数)
如果要按照降序排序
则o1 小于o2,返回(正数),相等返回0,01大于02返回(负数)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| package com.itheima.demo05.Collections;
import java.util.ArrayList; import java.util.Collections;
public class Demo02Sort { public static void main(String[] args) { ArrayList<Integer> list01 = new ArrayList<>(); list01.add(1); list01.add(3); list01.add(2); System.out.println(list01);
Collections.sort(list01);
System.out.println(list01);
ArrayList<String> list02 = new ArrayList<>(); list02.add("a"); list02.add("c"); list02.add("b"); System.out.println(list02);
Collections.sort(list02); System.out.println(list02);
ArrayList<Person> list03 = new ArrayList<>(); list03.add(new Person("张三",18)); list03.add(new Person("李四",20)); list03.add(new Person("王五",15)); System.out.println(list03);
Collections.sort(list03); System.out.println(list03); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| package com.itheima.demo05.Collections;
public class Person implements Comparable<Person>{ private String name; private int age;
public Person() { }
public Person(String name, int age) { this.name = name; this.age = age; }
@Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; }
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; }
@Override public int compareTo(Person o) { return o.getAge() - this.getAge(); } }
|