s-day03--Collections里面的sort方法以及Comparable接口
This commit is contained in:
@@ -0,0 +1,28 @@
|
|||||||
|
package com.inmind.colletions04;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
/*
|
||||||
|
7.Collections里面的sort方法以及Comparable接口
|
||||||
|
public static <T> void sort(List<T> list):将集合中元素按照默认规则排序。
|
||||||
|
|
||||||
|
注意:
|
||||||
|
1.要使用以上的排序api,那么List集合的泛型的类型必须实现Comparable接口.
|
||||||
|
2.当一个类实现了Comparable接口就表示该类具有了自然排序功能
|
||||||
|
|
||||||
|
*/
|
||||||
|
public class Demo13 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
ArrayList<Student> students = new ArrayList<>();
|
||||||
|
Collections.addAll(students
|
||||||
|
, new Student("张三1", 19)
|
||||||
|
, new Student("张三2", 20)
|
||||||
|
, new Student("张三3", 18)
|
||||||
|
, new Student("张三4", 21)
|
||||||
|
);
|
||||||
|
System.out.println(students);
|
||||||
|
//希望集合的学生按年龄排序(升序,降序)
|
||||||
|
Collections.sort(students);
|
||||||
|
System.out.println(students);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package com.inmind.colletions04;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public class Student implements Comparable<Student> {
|
||||||
|
String name;
|
||||||
|
int age;
|
||||||
|
|
||||||
|
public Student(String name, int age) {
|
||||||
|
this.name = name;
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Student{" +
|
||||||
|
"name='" + name + '\'' +
|
||||||
|
", age=" + age +
|
||||||
|
'}';
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (o == null || getClass() != o.getClass()) return false;
|
||||||
|
|
||||||
|
Student student = (Student) o;
|
||||||
|
return age == student.age && Objects.equals(name, student.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
int result = Objects.hashCode(name);
|
||||||
|
result = 31 * result + age;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
排序功能方法
|
||||||
|
我-它:升序
|
||||||
|
它-我:降序
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public int compareTo(Student s) {
|
||||||
|
// return this.age-s.age;//升序
|
||||||
|
return s.age-this.age;//降序
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user