java ArrayList的兩種排序方法
阿新 • • 發佈:2019-02-14
1.ArrayList使用排序的初衷
我們知道ArrayList的好處是可以不用限定容器的大小,他會根據元素的增加自己擴大。但是儲存進去的資料型別都會變成object,雖然每個元素有自己的index,但不像陣列的下標可以更加方便的操作。那我們平時學習的選擇排序啊快速排序啊都是對陣列進行操作。最開始的笨辦法就是把list中的資料傳給陣列排序好了再傳回來嘍。但是這樣效率真的下降的不是幾倍,是幾十倍啊真的不能這樣來。查了點資料和案例在這裡總結一下。
2.對一個ArrayList中的陣列進行排序。
首先來看下Collection的幫助文件:
在這裡順便補充下ArrayList和Collection的關係:
具體的使用程式碼如下:
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class compre { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan=new Scanner(System.in); int n; ArrayList al=new ArrayList(); System.out.println("請輸入需要的個數"); n=scan.nextInt(); System.out.println("請逐一輸入"); for(int i=0;i<n;i++) { al.add(i,scan.nextInt()); } System.out.println("你輸入的數字是:"); for(int i=0;i<al.size();i++) { int temp=(int)al.get(i); System.out.print(temp+" "); } Collections.sort(al);//針對一個ArrayList內部的資料排序 System.out.println(); System.out.println("經過排序後:"); for(int i=0;i<al.size();i++) { int temp=(int)al.get(i); System.out.print(temp+" "); } } }
執行結果:
2.多個ArrayList中的元素進行排序
class SortByName implements Comparator {
public int compare(Object o1, Object o2) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
return s1.getName().compareTo(s2.getName());
}
}
class SortByAge implements Comparator { public int compare(Object o1, Object o2) { Student s1 = (Student) o1; Student s2 = (Student) o2; return s1.getAge().compareTo(s2.getAge()); // if (s1.getAge() > s2.getAge()) // return 1; // return -1; } }