以下是代码:- public class GenericDemo7 {
- public static void main(String[] args)
- {
- TreeSet<Student3> ts=new TreeSet<Student3>(new Comp());
- ts.add(new Student3("abc03"));
- ts.add(new Student3("abc02"));
- ts.add(new Student3("abc06"));
- ts.add(new Student3("abc01"));
- Iterator<Student3> it=ts.iterator();
- while(it.hasNext())
- {
- System.out.println(it.next().getName());
- }
- }
- }
复制代码- class Comp implements Comparator<Student3>
- {
- public int compare(Student3 s1,Student3 s2)
- {
- return s1.getName().compareTo(s2.getName());
- }
- }
复制代码- class Person3
- {
- private String name;
- Person3(String name)
- {
- this.name=name;
- }
- public String getName() {
- return name;
- }
- public String toString()
- {
- return "person:"+name;
- }
- }
复制代码- class Student3 extends Person3
- {
- Student3(String name) {
- super(name);
- }
- }
复制代码 这里的Comp类里面怎么可以用compareTo方法?没实现Comparable接口啊。
|
|