本帖最后由 黄敏 于 2012-8-16 00:38 编辑
class Student implements Comparable<Student>{
private String name;
private int age;
private int score;
public Student(String name, int age){
this.setName(name);
this.setAge(age);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String toString(){
return "姓名: " + this.name + ",年龄: " + this.age ;
}
public int hashCode(){
return name.hashCode()+ age*13;
}
public boolean equals(Object obj){
if (!(obj instanceof Student))
throw new RuntimeException();
Student stu = (Student) obj;
return this.name.equals(stu.name)&& this.age==stu.age ;
}
public int compareTo(Student stu){
if (this.getAge() > stu.getAge())
return -1;
if(this.score== stu.score){
stu.getName().compareTo(this.getName());
}
return 1;
}
}
class MyComparator implements Comparator<Student>{
public int compare(Student o1, Student o2){
int n = new Integer(o1.getAge()).compareTo(new Integer(o2.getAge()));
if(n==0)
return o1.getName().compareTo(o2.getName());
return n;
}
}
public class Test10 {
public static void main(String[] args) {
TreeMap<Student, Integer> mp = new TreeMap<Student, Integer>();
mp.put(new Student("张三",17), 89);
mp.put(new Student("李四",18), 90);
mp.put(new Student("马六",18), 97);
mp.put(new Student("王五",17), 91);
//第一种取出方式:keySet
Set<Student> se = mp.keySet();
Iterator<Student> it = se.iterator();
while (it.hasNext()){
Student stu =it.next();
int val = mp.get(stu); //运行到这的时候出现NullPointerException异常,求真相,没找出来什么原因,我也么发现我哪里写错了啊
System.out.println(stu +",成绩: "+ val);
}
}
}
|