java中用Comparator比较器对ArrayList排序

转载至Comparator比较器对ArrayList排序

boy 男生 对象

public class Boy {
	String name;//姓名
	int score;// 分数
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getScore() {
		return score;
	}
	public void setScore(int score) {
		this.score = score;
	}
}

Comparator强行对某个对象collection进行整体排序的比较函数,可以将Comparator传递给Collections.sort或Arrays.sort。

比较算法

import java.util.Comparator;
 
public class MyComparator implements Comparator {
 
	//接口,必须实现的方法
	public int compare(Object o1, Object o2) {
		Boy p1 = (Boy) o1;
		Boy p2 = (Boy) o2;
		if (p1.score < p2.score)
			return 1;
		else if (p1.score > p2.score)
			return -1;
		else
			return 0;
	}
}

实际运用

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class ScoreSort{
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		List boys = new ArrayList();
		Boy b = new Boy();
		b.name = "tom";
		b.score = 89;
		boys.add(b);
 
		b = new Boy();
		b.name = "jim";
		b.score = 92;
		boys.add(b);
 
		b = new Boy();
		b.name = "jack";
		b.score = 77;
		boys.add(b);
 
		for(int i=0 ;i < boys.size();i++){
			b = (Boy)boys.get(i);
			System.out.println(b.name + " : " + b.score);
		}
 
		System.out.println("------------------------");
 
		MyComparator mc = new MyComparator();
		Collections.sort(boys,mc);  
 
		for(int i=0 ;i < boys.size();i++){
			b = (Boy)boys.get(i);
			System.out.println(b.name + " : " + b.score);
		}
 
 
 
	}
 
}



你可能感兴趣的:(java,算法,排序,comparator)