本帖最后由 史政法 于 2013-3-1 21:01 编辑
- import java.util.*;
- class Student implements Comparable
- {
- private String name;
- private int age;
-
- public int compareTo(Object obj)
- {
- if (!(obj instanceof Student))
- {
- throw new RuntimeException("No Student Class");
- }
- Student s = (Student)obj;
- if (this.age>s.age)//这里接收的一个Object类进来,并进行强转动作,为什么能直接调用私有成员s.age
- {
- return 1;
- }
- if (this.age==s.age)
- {
- return this.name.compareTo(s.name);
- }
- return -1;
- }
- public Student(String name ,int age)
- {
- this.name = name;
- this.age = age;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- }
- class MyComparator implements Comparator
- {
- public int compare(Object o1,Object o2)
- {
- if (!(o1 instanceof Student && o2 instanceof Student))
- {
- throw new RuntimeException("No Student...");
- }
- Student s = (Student)o1;
- Student s2 = (Student)o2;
- int num = s.name.compareTo(s2.name);//这里同样接收的是Objcet类,也做了强转动作,为什么不能使用私有成员。他们之间区别在哪里?内存中是怎样的?
- if (num ==0 )
- {
- new Integer(s.age).compareTo(new Integer(s2.age));
- }
- return num;
- }
- }
- class TreeSetDemo2
- {
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet(new MyComparator());
- ts.add(new Student ("abc",10));
- ts.add(new Student ("bac",11));
- ts.add(new Student ("cab",12));
- ts.add(new Student ("acb",13));
- for (Iterator it = ts.iterator();it.hasNext() ; )
- {
- sop(it.next());
- }
- }
- public void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
复制代码 问题详情见代码。。。。。。
|
|