java用比较器comparable接话把现类似excel排序

java用比较器comparable接口实现类似excel排序

题目要求:设计一个学生类,此类包含姓名、年龄、成绩,并产生一个对象数组,要求按成绩由高到低排序,如果成绩相等,则按年龄由低到高排序。

在java中有个排序sort可以调用此函数来实现。arrays类中的sort可以对任意类型的数组排序,当然可以对object数组排序,要求是该对象数组必须实现comparable接口。

public interface Comparable<T>{
     public int compareTo(T o);
}

 

compareTo方法返回一个int类型

+++1:表示大于

+++-1:表示小于

+++0:表示等于

运用比较器进行排序实现代码

package ch11;

import java.util.Arrays;

/**
 * @author 作者  bin
 * @version 创建时间:2011-1-20 下午09:22:32
 * 类说明
 */
class Student implements Comparable<Student>{
	private String name;
	private int age;
	private float score;
	public int compareTo(Student student){
		if(this.score>student.score){
			return -1;
		}else if(this.score<student.score){
			return 1;
		}else{
			if(this.age>student.age){
				return 1;
			}else if(this.age<student.age){
				return -1;
			}else{
				return 0;
			}
		}
	}
	public Student(String name,int age,float score){
		this.name = name;
		this.age = age;
		this.score = score;
	}
	public String toString(){
		return name+"\t\t"+age+"\t\t"+score;
	}
}
public class MyComparable {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Student[] stu ={
				new Student("胡斌",22,98),
				new Student("张三",22,93),
				new Student("李四",20,93),
				new Student("王五",22,100),
				new Student("tao哥",21,77),
				new Student("jia宝",53,(float) 69.5),
		};
		Arrays.sort(stu);
		for(int i =0;i<6;i++){
			System.out.println(stu[i]);
		}

	}

}

 运行结果:

王五  22  100.0
胡斌  22  98.0
李四  20  93.0
张三  22  93.0
tao哥  21  77.0
jia宝  53  69.5

1 楼 tangzlboy 2012-05-14  
java用比较器comparable接话把现类似excel排序