package pack2;
import java.util.*;
public class Student {
public static void main(String[] args) {
Student student = new Student();
student.Student11();
student.Teache();
}
public void Teache(){
Teacher t = new Teacher();
t.setAge(35);
t.setName("肖老师");
t.setSex("男");
t.run();
}
public void Student11(){
List<Student1> list = new ArrayList<Student1>();
Student1 s1 = new Student1();
s1.setId(1);
s1.setName("巫妖王");
s1.setScore(100);
s1.setAge(127);
list.add(s1);
Student1 s2 = new Student1();
s2.setId(2);
s2.setName("阿拉斯");
s2.setScore(13);
s2.setAge(34);
list.add(s2);
Student1 s3 = new Student1();
s3.setId(3);
s3.setName("关羽");
s3.setScore(55);
s3.setAge(77);
list.add(s3);
// Collections.sort(list);
Collections.sort(list,Collections.reverseOrder()); //降序
for(Student1 s:list){
System.out.println(s.toString());
}
}
}
/*-------------------------------------------------------*/
package pack2;
public class Student1 implements Comparable{
private String name;
private double score;
private int age;
private int Id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getId() {
return Id;
}
public void setId(int Id) {
this.Id = Id;
}
public boolean equals(Object o){
Student1 s = (Student1)o;
if(this.getId() == s.getId()){
return true;
}else{
return false;
}
}
public int compareTo(Object o) {
Student1 s = (Student1)o;
if(this.getScore() < s.getScore()){
return 1;
}else{
return 0;
}
}
public String toString(){
return this.getName()+"的年龄是:"+this.getAge()+
" 成绩是:"+this.getScore();
}
public int hashCode(){
return this.getId()+this.getName().hashCode();
}
}
出来的他的 成绩 和 年龄应该是按照降序的方式排列的啊 为什么没什么效果过啊 请大牛指点 谢谢
------解决方案--------------------
- Java code
public int compareTo(Object o) { Student1 s = (Student1) o; if (this.getScore() < s.getScore()) {//小于的时候返回负数 return -1; } else if(this.getScore()>s.getScore())//大于的时候返回正数 { return 1; }else //等于返回0 { return 0; } }