【Java基础篇】集合排序
生活随笔
收集整理的這篇文章主要介紹了
【Java基础篇】集合排序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
所謂集合排序是指對集合內的元素進行排序。
集合工具類Collections中提供了兩種排序算法,分別是:
Collections.sort(List list)這種方式需要對象實現Comparable接口,并重寫compareTo()方法。
import java.util.Collections; import java.util.LinkedList;public class Student implements Comparable<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 + "]";}@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,"王五");LinkedList<Student> list = new LinkedList<Student>();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,"王五");LinkedList<Student> list = new LinkedList<Student>();list.add(stu);list.add(stu2);list.add(stu3);Collections.sort(list,new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {return o2.getId()-o1.getId();}});for(Student student:list){System.out.println(student);}} }?
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的【Java基础篇】集合排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用什么指标看是不是一只好基金 看评级还
- 下一篇: mysql sqlstate 08001