java 对象排序--Comparable

1. 要求

对象student(id,name,sex,scroe,old);先按scroe排序,当scroe值相同时按old排序

 

2.解决办法,通过Arrays.sort(Object[])静态方法实现,但是对象需要实现Comparable

 

3.studen.java

public class Student implements Comparable {

	private Integer id;
	private String name;
	private String sex;
	private double score;
	private Integer old;
	
	public Student(Integer _id,String _name,String _sex,double _score,Integer _old){
		this.setId(_id);
		this.setName(_name);
		this.setSex(_sex);
		this.setScore(_score);
		this.setOld(_old);
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public double getScore() {
		return score;
	}

	public void setScore(double score) {
		this.score = score;
	}

	public Integer getOld() {
		return old;
	}

	public void setOld(Integer old) {
		this.old = old;
	}

	@Override
	public int compareTo(Object o) {
		Student others = (Student) o;
		if (this.score > others.score)
			return -1;
		else if (this.score == others.score) {
			if (this.old > others.old)
				return -1;
			else if (this.old == others.old)
				return 0;
			else
				return 1;
		} else
			return 1;
	}
}

 

说明:compareTo(Object o) 根据jdk API是

比较此对象与指定对象的顺序。如果该对象小于、等于或大于指定对象,则分别返回负整数、零或正整数。 

 

4.测试类StudentSortDemo.java

public class StudentSortDemo {

	public static void main(String[] args) {
		Student[] student = {
                new Student(1,"Daffy","m",88, 23),   
                new Student(2,"Dewey","w",69, 44),
                new Student(3,"Howard","m",66, 32),   
                new Student(4,"Louie","w",78, 25),   
                new Student(5,"Donald","m",69, 30),   
                new Student(6,"Huey","w",55, 24)   
        };   
           
        System.out.println("Before sorting:");   
        display(student); 
           
        Arrays.sort(student);
           
        System.out.println("\nAfter sorting:");   
        display(student);   
    }   
       
    public static void display(Student[] student){   
        for (int i = 0; i < student.length; i++) {
            System.out.println("name:" + student[i].getName()+",score:"+student[i].getScore()+",old:"+student[i].getOld());
        }   
    }   
}

 

输出结果为:

Before sorting:
name:Daffy,score:88.0,old:23
name:Dewey,score:69.0,old:44
name:Howard,score:66.0,old:32
name:Louie,score:78.0,old:25
name:Donald,score:69.0,old:30
name:Huey,score:55.0,old:24

 

After sorting:
name:Daffy,score:88.0,old:23
name:Louie,score:78.0,old:25
name:Dewey,score:69.0,old:44
name:Donald,score:69.0,old:30
name:Howard,score:66.0,old:32
name:Huey,score:55.0,old:24 

 

 

你可能感兴趣的:(java,jdk)