1. 程式人生 > >java對ArrayList中的元素自定義排序

java對ArrayList中的元素自定義排序

        任何類只要實現了Comparable介面就可以呼叫java提供的Array.sort()函式或是是Collections.sort()函式對一個物件列表排序,在重寫Comparable中的函式是我們可以自定義對列表的排序方式,比如要對一個學生列表先按年齡排序,然後如果年齡相同的話就按姓名的字典序排序,甚至可以新增更多的排序條件。一些就以這個例子用java程式碼簡單實現一下。

我們要對學生排序,首先就要定義學生Student物件,並且要實現Comparable介面,從字面上就能很明顯的看出,只有實現了該接口才有可比性嘛!哈哈

定義Student類:

<pre name="code" class="java">class Student implements Comparable<Student> {//因為在ArrayList中使用了泛型,所以要在此用<>表明型別,比如是對String類實現的介面就寫String    
    String name;    
    int age;    
    
    public Student(String name, int age) {    
        super();    
        this.name = name;    
        this.age = age;    
    }    
        
    public int compareTo(Student tempStudent) {//從寫介面中的函式    
    if (this.age != tempStudent.age) {//當年齡不相同時,則只按年齡的大小對學生進行排序    
        return this.age - tempStudent.age;//交換兩者的順序可以實現是升序還是降序    
    }    
    else {//如果兩個學生的年齡相同,那麼我們就按其姓名排序    
        if (!this.getName().equals(tempStudent.getName())) {//如果前幾個字母都一樣,我們就不能進行比較,所以要對第一個不同的字母進行比較    
            int i = 0;    
            while (i < this.name.length() && i < tempStudent.getName().length()) {//使用循序找到第一個不同的字母    
                if (this.name.charAt(i) != tempStudent.getName().charAt(i))    
                    break;    
                i++;    
            }    
            return this.name.charAt(i) - tempStudent.getName().charAt(i);//返回名字的比較值    
        }    
        else//當名字相同是    
            return -1;//順便返回一個值,因為這不會影響排序的結果,只是為了與前面的if搭配    
    }    
}    
    
public String toString() {    
    return "name=" + name + ", age=" + age;    
}    
    
public String getName() {    
    return this.name;    
}   


        上面定義了Student類,下面我們將Student類的物件新增的ArrayList的物件中,並是用sort函式排序:

包含main方法的類:

public class arraylist的使用 {

	public static void main(String[] args) {
		ArrayList<Student> stuList = new ArrayList<Student>(20);//設定stuList的接受型別是Student,設定預設容量是20個元素 
		stuList.add(new Student("ciong", 21));
		stuList.add(new Student("xanarry", 11));
		stuList.add(new Student("amith", 21));
		stuList.add(new Student("jason", 19));
		stuList.add(new Student("marray", 25));
		stuList.add(new Student("blex", 21));//新增6個學生到stuList中
		
		System.out.println("---original order---");
		
		for (Iterator<Student> iterator = stuList.iterator(); iterator.hasNext(); ) {//使用迭代器遍歷輸入所有學生資訊
			System.out.println(iterator.next());
		}
		
		//使用sort函式排序
		//寫法1:
		stuList.sort(null);
		///寫法2:
		Collections.sort(stuList);
		
		System.out.println("---sorted---");
		for (Iterator<Student> iterator = stuList.iterator(); iterator.hasNext(); ) {//輸入有序結果
			System.out.println(iterator.next());
		}
	}
}

         兩次的輸出結果如下:
---original order---
name=ciong, age=21
name=xanarry, age=11
name=amith, age=21
name=jason, age=19
name=marray, age=25
name=blex, age=21

          排序後:
---sorted---
name=xanarry, age=11
name=jason, age=19
name=amith, age=21
name=blex, age=21
name=ciong, age=21
name=marray, age=25