diff --git a/s-day03/src/com/inmind/collections04/Demo14.java b/s-day03/src/com/inmind/collections04/Demo14.java new file mode 100644 index 0000000..3903fbd --- /dev/null +++ b/s-day03/src/com/inmind/collections04/Demo14.java @@ -0,0 +1,39 @@ +package com.inmind.collections04; + +import java.util.ArrayList; +import java.util.Collections; + +/* +static > void sort(List list) 根据其元素的自然排序,按照升序排列指定的列表。 + */ +public class Demo14 { + public static void main(String[] args) { + //整数的自然排序,默认升序 + ArrayList lists = new ArrayList<>(); + Collections.addAll(lists, 111, 22, 32, 4, 555); + System.out.println(lists); + //对集合进行排序 + Collections.sort(lists); + System.out.println(lists); + System.out.println("-------------------------------------"); + //字符串的默认排序,按照字典排序,按ASCII码值 + ArrayList strs = new ArrayList<>(); + Collections.addAll(strs, "ab", "ba", "aa", "ca", "ac","bb"); + System.out.println(strs); + //对集合进行排序 + Collections.sort(strs); + System.out.println(strs); + + //自定义类的排序(Student) + ArrayList students = new ArrayList<>(); + students.add(new Student("张三1", 18,88)); + students.add(new Student("张三2", 18,90)); + students.add(new Student("张三3", 18,93)); + students.add(new Student("张三4", 18,39)); + System.out.println(students); + //注意:Collections.sort排序时,传入的集合的内容,必须拥有自然排序功能(实现Comparable) + Collections.sort(students); + System.out.println(students); + + } +} diff --git a/s-day03/src/com/inmind/collections04/Student.java b/s-day03/src/com/inmind/collections04/Student.java new file mode 100644 index 0000000..aed7ee8 --- /dev/null +++ b/s-day03/src/com/inmind/collections04/Student.java @@ -0,0 +1,39 @@ +package com.inmind.collections04; + +public class Student implements Comparable{ + String name; + int age; + int score; + + public Student(String name, int age, int score) { + this.name = name; + this.age = age; + this.score = score; + } + + @Override + public String toString() { + return "Student{" + + "name='" + name + '\'' + + ", score=" + score + + '}'; + } + + /* + 排序口诀: + 我(this)-它(参数o):升序 + 它-我:降序 + */ + @Override + public int compareTo(Student o) { +// return this.score - o.score; //升序 + /* if (this.score > o.score) { + return -1; + } else if (this.score < o.score) { + return 1; + } else { + return 0; + }*/ + return o.score - this.score; + } +}