大家主要看PrintColl( )这个方法有没有问题就行
/*定义一个Person类,用泛型是实现可以接受Person类本身及其子类。
*/
import java.util.*;
class Person implements Comparable
{
private String name;
private int age;
Person(String name,int age)
{
this.name=name;
this.age=age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public int compareTo(Object obj)
{
Person p=(Person)obj;
int num=this.name.compareTo(p.name);
if(num==0)
return new Integer(this.age).compareTo(new Integer(p.age));
return num;
}
}
class Worker extends Person
{
Worker(String name,int age)
{
super(name,age);
}
}
class Student extends Person
{
Student(String name,int age)
{
super(name,age);
}
}
class PersonGeneric
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
/*TreeSet ts=new TreeSet();
ts.add(new Person("zhangsan",80));
ts.add(new Person("zhangsan",21));
ts.add(new Person("lisi",22));
ts.add(new Person("wangwu",18));*/
TreeSet<Person> ts2=new TreeSet<Person>(new myCompar());
ts2.add(new Person("zhangsan",8888888));
ts2.add(new Person("zhangsan",21));
ts2.add(new Person("lisi",22));
ts2.add(new Person("wangwu",18));
Iterator<Person> it=ts2.iterator();
while(it.hasNext())
{ Person p=it.next();
System.out.println(p.getName()+":::"+p.getAge());
}
//printColl(al);
}
/*public static void printColl(ArrayList<?> al)
{
Iterator<Person> it=al.iterator();
while(it.hasNext())
{ Person p=it.next();
System.out.println(p.getName()+":::"+p.getAge());
}
}*/
}
//;比较器
class myCompar implements Comparator<Person>
{
public int compare(Person o1,Person o2)
{
//Person p1=(Person)o1;
//Person p2=(Person)o2;
//return p1.getName().compareTo(p2.getName());
return o1.getName().compareTo(o2.getName());
}
} |