覆写JAVA中的CompareTo()方法与toString()方法的实现

package org.lza;

import java.util.Arrays;

public class ComparableDemo {
	public static void main(String args[]){
		Student stu[]={new Student("张三",20,90.0f),new Student("李四",22,90.0f),new Student("王五",20,99.0f),new Student("赵六",20,70.0f)};
		Arrays.sort(stu);
		for(Student st:stu)
			System.out.println(st);
	}
}
class Student implements Comparable 
{
	private String name;
	private int age;
	private float score;
	public Student(String name,int age,float score){
		this.name=name;
		this.age=age;
		this.score=score;
	}
	@Override
	public String toString(){
		//覆写字符串转换方法
		return name+"\t\t"+this.age+"\t\t"+this.score;
	}
	/*
	 * 排序要求 成绩由高到低 成绩相等则按年龄由低到高
	 * @see java.lang.Comparable#compareTo(java.lang.Object)
	 */
	@Override
	public int compareTo(Student stu){
		//覆写compareTO()方法,实现排序规则的应用
		if(this.score>stu.score){	//分高的往数组前面走
			return -1;
		}else if(this.scorestu.age){
				return 1;
			}else if(this.age


 

你可能感兴趣的:(Java)