1. 程式人生 > >Java中ArrayList的排序兩種方法以及遍歷的程式碼

Java中ArrayList的排序兩種方法以及遍歷的程式碼

方法一:

  • 在類的定義中實現Comparable介面中的compareTo()方法,然後呼叫Collections.sort()進行排序:
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
class Student implements Comparable{//使用Comparable介面
     String name;
     int score;
    public Student(String name,int
score) { this.name=name; this.score=score; } @Override public int compareTo(Object o) {//使用Comparable的compareTo方法 // TODO Auto-generated method stub Student s=(Student) o;// Object類確定為Student類 return s.score-this.score;//決定排序的順序 } } public class
Main{
public static void main(String[] args){ ArrayList<Student> list=new ArrayList<Student>(); list.add(new Student("bbb",30)); list.add(new Student("aaa",15)); list.add(new Student("ccc",80)); Collections.sort(list);//排序
Iterator<Student> it=list.iterator();//迭代器輸出 while(it.hasNext()) { Student s=(Student) it.next(); //轉換為Student類 System.out.printf("%s %d\n",s.name,s.score); } } }

方法二:

  • 建立一個新類,實現Comparator,主函式中呼叫Collections.sort(要處理的集合的名字,new新類())
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
class Student {
     String name;
     int score;
    public Student(String name,int score)
    {
        this.name=name;
        this.score=score;   
    }
}
class Stu implements Comparator<Student>{
    @Override
    public int compare(Student o1, Student o2) {
        // TODO Auto-generated method stub
        return o1.score-o2.score;//決定排序的順序
    }   
}

public class Main{
        public static void main(String[] args){

            ArrayList<Student> list=new ArrayList<Student>();
        list.add(new Student("bbb",30));
        list.add(new Student("aaa",15));
        list.add(new Student("ccc",80));
        Collections.sort(list,new Stu());//排序方法
            Iterator<Student> it=list.iterator();//迭代器輸出
            while(it.hasNext())
            {
                Student s=(Student) it.next();  //轉換為Student類
                System.out.printf("%s %d\n",s.name,s.score);
        }
      }
}