- import java.util.*;
- class Demo
- {
- public static void main(String[] args)
- {
- TreeSet<Student> ts = new TreeSet<Student>(new MyComparator());
- ts.add(new Student("12",20));
- ts.add(new Student("32",20));
- ts.add(new Student("34",23));
- ts.add(new Student("12",20));
- ts.add(new Student("12",20));
- for(Student s : ts)
- {
- println.sop(s.toString());
- }
- }
- }
- class MyComparator implements Comparator<Student>
- {
- public int compare(Student s1 ,Student s2)
- {
- int num = s1.getName().compareTo(s2.getName());
- if(num == 0)
- return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
- return num;
- }
- }
- class Student implements Comparable<Student>
- {
- private String name;
- private int age;
- Student(String namr,int age)
- {
- this.name = name;
- this.age = age;
- }
- public void setName(String name)
- {
- this.name = name;
- }
- public void setAge(int age)
- {
- this.age = age;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- public boolean equals(Object obj)
- {
- if(!(obj instanceof Student))
- throw new RuntimeException("数据类型错误");
- Student s = (Student)obj;
- return this.name.equals(s.name) && this.age == s.age;
- }
- public int hashCode()
- {
- return name.hashCode()+age*13;
- }
- public int compareTo(Student s)
- {
- Integer num = this.name.compareTo(s.name);
- if(num == 0)
- return new Integer(this.age).compareTo(new Integer(s.age));
- return num;
- }
- public String toString()
- {
- return "姓名:"+name+",年龄:"+age;
- }
- }
复制代码
。。。不知道怎么死的,,,,这不科学锕。。。怎么会出现控空指针异常呢?
求解释
|
|