Sắp xếp các đối tượng sử dụng phương thức Collection.sort

Lập trình viên thường phải sắp xếp một tập hợp các dữ liệu đầu vào. Java đã có sẵn một tập hợp các API cho việc sắp xếp. Trong java, khi chúng ta muốn so sánh nhiều đối tượng thuộc một class thì class đó cần phải thi hành interface Comparable. Các lớp sẵn có của java như Integer, Date cũng thi hành interface này, dó đó những dối tượng thuộc những lớp trên có thể dễ dàng được sắp xếp dựa vào phương thức Collection.sort. Chúng ta cũng có thể thi hành interfaceComparable để các đối tượng của class đó có thể sắp xếp bằng phương thức Collection.sort

package test;
import java.util.ArrayList;

import java.util.Collections;

import java.util.Iterator;

import java.util.List;

public class ListExample {

	List list;

	public ListExample() {

		list = new ArrayList();

	}

	private List getList() {

		return list;

	}

	public static void main ( String [] args ) {

		ListExample lExam = new ListExample();

		List tempList = lExam.getList();

		tempList.add(new Car(2));

		tempList.add(new Car(3));

		tempList.add(new Car(1));

		tempList.add(new Car(6));

		Collections.sort(tempList);

		Iterator iterator = lExam.getList().iterator();

		while (iterator.hasNext()) {

			System.out.println(((Car)iterator.next()).getCapacity());

		}

	}

}
package test;class Car implements Comparable{

	int capacity;public Car(int c){

		this.capacity=c;

	}

	public int compareTo(Object o) {

		int thisVal = this.capacity;

		int anotherVal = ((Car)o).capacity;

		return (thisVal<anotherval (thisval="=anotherVal">
		</anotherval>
	}

	public int getCapacity(){

		return capacity;

	}

}

Output :

	1

	2

	3

	6

(java-tips)

Leave a Reply