java 集合 实现comparable接口


import java.util.Scanner;
import java.util.TreeSet;

/*
 * 编写一个学生成绩管理程序;
 * 学生的属性包括学号、姓名、年龄、成绩等;
 * 请根据学生学号、姓名、年龄、成绩等进行排序;
 */
public class Test 
{
public static void main(String[] args) 
{
Scanner scan = new Scanner(System.in);
int[] id = new int[6];
String[] name = new String[6];
int[] age = new int[6];
double[] score = new double[6];
TreeSet ts = new TreeSet();
String str;
System.out.println("input id,name,age,score:");
for(int i=0; i<6; i++) //在控制台上输入六个学生的信息;
{
str = scan.next();
String[] str1 = str.split(",");
id[i] = Integer.valueOf(str1[0]);
name[i] = str1[1];
age[i] = Integer.valueOf(str1[2]);
score[i] = Double.valueOf(str1[3]);
ts.add(new Student(id[i], name[i], age[i], score[i]));
}
for(Student x:ts)   //使用foreach输出;
{
System.out.println(x);
}
}

}



public class Student implements Comparable
{
int id;
String name;
int age;
double score;
public Student(int id, String name, int age, double score)
{
this.id = id;
this.name = name;
this.age = age;
this.score = score;
}

public int getId()
{
return id;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public double getScore()
{
return score;
}


@Override
public String toString() //重写toString方法,调用时按以下方式输出;
{
return "id=" + id + ", name=" + name + ", age=" + age + ", score=" + score;
}
@Override
public int compareTo(Student s)     //重写compareTo方法,升序排序,若id相同,则依次往name、age、score推;
{
int num;
num = id > s.id ? 1 : (id == s.id ? 0 : -1);
if(num==0)
{
int n = this.name.compareTo(s.name);
if(n > 0)
{
num = 1;
}
else if(n == 0)
{
num = age > s.age?1:(age==s.age?0:-1);
if(num == 0)
{
num = score > s.score ? 1 : (score==s.score?0:-1);
}
}
else
{
num = -1;
}
}
return num;
}
}

你可能感兴趣的:(Java)