A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 黄泉 中级黑马   /  2014-6-3 14:48  /  1232 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. import java.util.*;

  2. class Demo
  3. {
  4.         public static void main(String[] args)
  5.         {
  6.                 TreeSet<Student> ts = new TreeSet<Student>(new MyComparator());
  7.                 ts.add(new Student("12",20));
  8.                 ts.add(new Student("32",20));
  9.                 ts.add(new Student("34",23));
  10.                 ts.add(new Student("12",20));
  11.                 ts.add(new Student("12",20));

  12.                 for(Student s : ts)
  13.                 {
  14.                         println.sop(s.toString());
  15.                 }
  16.         }
  17. }

  18. class MyComparator implements Comparator<Student>
  19. {
  20.         public int compare(Student s1 ,Student s2)
  21.         {
  22.                 int num = s1.getName().compareTo(s2.getName());

  23.                 if(num == 0)
  24.                         return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));

  25.                 return num;
  26.         }
  27. }

  28. class Student implements Comparable<Student>
  29. {
  30.         private String name;
  31.         private int age;
  32.         Student(String namr,int age)
  33.         {
  34.                 this.name = name;
  35.                 this.age = age;
  36.         }

  37.         public void setName(String name)
  38.         {
  39.                 this.name = name;
  40.         }
  41.         public void setAge(int age)
  42.         {
  43.                 this.age = age;
  44.         }

  45.         public String getName()
  46.         {
  47.                 return name;
  48.         }
  49.         public int getAge()
  50.         {
  51.                 return age;
  52.         }

  53.         public boolean equals(Object obj)
  54.         {
  55.                 if(!(obj instanceof Student))
  56.                         throw new RuntimeException("数据类型错误");

  57.                 Student s = (Student)obj;

  58.                 return this.name.equals(s.name) && this.age == s.age;
  59.         }

  60.         public int hashCode()
  61.         {
  62.                 return name.hashCode()+age*13;
  63.         }

  64.         public int compareTo(Student s)
  65.         {
  66.                 Integer num = this.name.compareTo(s.name);

  67.                 if(num == 0)
  68.                         return new Integer(this.age).compareTo(new Integer(s.age));

  69.                 return num;
  70.         }

  71.         public String toString()
  72.         {
  73.                 return "姓名:"+name+",年龄:"+age;
  74.         }
  75. }
复制代码
。。。不知道怎么死的,,,,这不科学锕。。。怎么会出现控空指针异常呢?

求解释

4 个回复

正序浏览
java里没有指针啊,C++里才有指针和引用啊
回复 使用道具 举报
自己好好看看单词有没写错
回复 使用道具 举报

你用的排序是comparetor,而他根本没有Student对象
回复 使用道具 举报
空指针异常
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马