本帖最后由 王超 于 2012-6-16 21:38 编辑
- import java.util.*;
- class StuNameComparator 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 int compareTo(Student s)
- {
- int num = new Integer(this.age).compareTo(new Integer(s.age));
- if(num==0)
- return this.name.compareTo(s.name);
- return num;
- }
- public int hashCode()
- {
- return name.hashCode()+age*34;
- }
- public boolean equals(Object obj)
- {
- if(!(obj instanceof Student))
- {
- throw new ClassCastException("类型不匹配");
- }
- Student s = (Student)obj;
- return this.name.equals(s.name) && this.age==s.age;
- }
- public String setName(String name)
- {
- return name;
- }
- public int setAge(int age)
- {
- return age;
- }
- public void getName(String name)
- {
- this.name = name;
- }
- public void getAge(int age)
- {
- this.age = age;
- }
- public String toString()
- {
- return name+":"+age;
- }
- }
- class MapTest2
- {
- public static void main(String[] args)
- {
- TreeMap<Student,String> tm = new TreeMap<Student,String>(new StuNameComparator());
- tm.put(new Student("blisi05",32),"beijing");
- tm.put(new Student("lisi06",52),"shanghai");
- tm.put(new Student("alisi02",49),"tianjin");
- tm.put(new Student("lisi01",25),"wuhan");
- Set<Map.Entry<Student,String>> entrySet = tm.entrySet();
- Iterator<Map.Entry<Student,String>> it = entrySet.iterator();
- while(it.hasNext())
- {
- Map.Entry<Student,String> me = it.next();
- Student stu = me.getKey();
- String addr = me.getValue();
- System.out.println(stu+"::"+addr);
- }
- }
- }
复制代码 错误提示:
MapTest2.java:12: 无法将 Student 中的 getName(java.lang.String) 应用于 ()
int num = s1.getName().compareTo(s2.getName());
^
MapTest2.java:12: 无法将 Student 中的 getName(java.lang.String) 应用于 ()
int num = s1.getName().compareTo(s2.getName());
^
MapTest2.java:15: 无法将 Student 中的 getAge(int) 应用于 ()
return new Integer(s1.getAge()).compareTo(new Integer(s2
.getAge()));
^
MapTest2.java:15: 无法将 Student 中的 getAge(int) 应用于 ()
return new Integer(s1.getAge()).compareTo(new Integer(s2
.getAge()));
^
4 错误 |
|