具有价值的做网站,怎么找人做网站啊,wordpress 文章审核,网件路由器无法登录所谓集合排序是指对集合内的元素进行排序。
集合工具类Collections中提供了两种排序算法#xff0c;分别是#xff1a;
Collections.sort(List list)Collections.sort(List list,Comparator c)
Collections.sort(List list)这种方式需要对象实现Comparable接口#xff0c;…所谓集合排序是指对集合内的元素进行排序。
集合工具类Collections中提供了两种排序算法分别是
Collections.sort(List list)Collections.sort(List list,Comparator c)
Collections.sort(List list)这种方式需要对象实现Comparable接口并重写compareTo()方法。
import java.util.Collections;
import java.util.LinkedList;public class Student implements ComparableStudent{private int id;private String name;public Student(int id, String name) {super();this.id id;this.name name;}public int getId() {return id;}public void setId(int id) {this.id id;}public String getName() {return name;}public void setName(String name) {this.name name;}Overridepublic String toString() {return Student [id id , name name ];}Overridepublic int compareTo(Student stu) {return stu.id-this.id;//实现id倒序}public static void main(String[] args) {Student stu new Student(2,张三);Student stu2 new Student(1,李四);Student stu3 new Student(5,王五);LinkedListStudent list new LinkedListStudent();list.add(stu);list.add(stu2);list.add(stu3);Collections.sort(list);for(Student student:list){System.out.println(student);}}
}Collections.sort(List list,Comparator c)这种方式比较灵活只需要提供比较器实例就可以了。
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;public class Student{private int id;private String name;public Student(int id, String name) {super();this.id id;this.name name;}public int getId() {return id;}public void setId(int id) {this.id id;}public String getName() {return name;}public void setName(String name) {this.name name;}Overridepublic String toString() {return Student [id id , name name ];}public static void main(String[] args) {Student stu new Student(2,张三);Student stu2 new Student(1,李四);Student stu3 new Student(5,王五);LinkedListStudent list new LinkedListStudent();list.add(stu);list.add(stu2);list.add(stu3);Collections.sort(list,new ComparatorStudent() {Overridepublic int compare(Student o1, Student o2) {return o2.getId()-o1.getId();}});for(Student student:list){System.out.println(student);}}
}