要排序元素,LinkedList可以使用Collections.sort(List<T> list)静态方法。排序的默认顺序是降序。
package org.nhooo.example.util; import java.util.LinkedList; import java.util.Collections; public class LinkedListSort { public static void main(String[] args) { LinkedList<String> grades = new LinkedList<>(); grades.add("E"); grades.add("C"); grades.add("A"); grades.add("F"); grades.add("B"); grades.add("D"); System.out.println("Before sorting:"); System.out.println("==============="); for (String grade : grades) { System.out.println("Grade = " + grade); } // 根据链接列表的数据对元素进行排序 // 自然秩序。 Collections.sort(grades); System.out.println("After sorting:"); System.out.println("==============="); for (String grade : grades) { System.out.println("Grade = " + grade); } } }
该程序的结果是:
Before sorting: =============== Grade = E Grade = C Grade = A Grade = F Grade = B Grade = D After sorting: =============== Grade = A Grade = B Grade = C Grade = D Grade = E Grade = F