本帖最后由 ゞ导火索゛ 于 2014-6-3 00:45 编辑
张三李四是字符串,不能作为参数实例化Integer,看你自己代码23句,还有14句的输出语句
- import java.util.*;
- class Demo
- {
- public static void main(String[] args)
- {
- TreeSet<Student> ts = new TreeSet<Student>(new MyComparator());
- ts.add(new Student("张三",20));
- ts.add(new Student("李四",25));
- ts.add(new Student("张三",22));
- for (Student s : ts)
- {
- System.out.println(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 name,int age)
- {
- this.name = name;
- this.age = age;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- public String toString()
- {
- return "姓名:"+name+",年龄"+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)
- {
- int num = new Integer(this.name).compareTo(new Integer(s.name));
- if(num == 0)
- return new Integer(this.age).compareTo(new Integer(s.age));
- return num;
- }
- }
复制代码
|