package com.itheima;
import java.util.Iterator;
import java.util.TreeSet;
public class Test10 {
public static void main(String[] args)throws NullPointerException{
// TODO Auto-generated method stub
TreeSet<Student> ts = new TreeSet<Student>();
ts.add(new Test10().new Student("wangwu01", 60.5, 23 ));
ts.add(new Test10().new Student("lisi06",90.3, 21));
ts.add(new Test10().new Student("zhangsan01", 56.5, 21));
ts.add(new Test10().new Student("zhangsan04", 80.5, 20));
ts.add(new Test10().new Student("wangwu05", 70.5, 19));
Iterator<Student> it = ts.iterator();
while(it.hasNext()){
Student s = (Student)it.next();
System.out.println("学生:"+s.getName()+"成绩:"+s.getScore()+"年龄:"+s.getage());
}
}
class Student implements Comparable<Object>
{
//定义学生具备的三个属性:姓名,分数和年龄
private String name;
private float score;
private int age;
//初始化学生的属性
Student(String name,float score,int age){
this.name = name;
this.score = score;
this.age = age;
}
public Student(String name2, double d, int age2) {
// TODO Auto-generated constructor stub
}
//实现Comparable接口的方法compareTo
@Override
public int compareTo(Object obj) {
// TODO Auto-generated method stub
//根据需求根据学生的成绩进行排序
//判断传入的对象是否Student对象
if(!(obj instanceof Student))
//如果不是学生对象就抛出异常
throw new RuntimeException("非学生");
//对传入的对象就行强转
Student stu = (Student)obj;
//比较两个学生的成绩大小如果相同,在调用字符串的compareTo方法进行排序
if(this.score == stu.score){
return this.name.compareTo(stu.name);
}
//分数如果不同,那就分数进行排序
if(this.score > stu.score){
return 1;
}
return -1;
}
//对外提供获得age属性的方法
public int getage(){
return age;
}
//对外提供获得name的方法
public String getName(){
return name;
}
//对外提供获得score的方法
public float getScore(){
return score;
}
}
}
下边是eclipse的提示:Exception in thread "main" java.lang.NullPointerException
at com.itheima.Test10$Student.compareTo(Test10.java:55)
at java.util.TreeMap.compare(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at com.itheima.Test10.main(Test10.java:10)
|