import java.util.*; class Person implements Comparable<Person>{ String name; int age; Person(){ name = ""; age = 0; } Person(String name, int age){ this.name = name; this.age = age; } public String toString(){ return name + "...." + age; } public int compareTo(Person o){ if(name.compareTo(o.name)==0) return o.age - age; return o.name.compareTo(name); } } class Student extends Person{ int score; public Student(){ super(); } public Student(String name, int age, int score){ super(name, age); this.score = score; } public String toString(){ return name + "...." + age + "...." + "score: " + score; } } class Worker extends Person{ int salary; public Worker(){ super(); } public Worker(String name, int age, int salary){ super(name, age); this.salary = salary; } public String toString(){ return name + "...." + age + "...." + "salary: " + salary; } } class ComparatorPerson implements Comparator<Person>{ public int compare(Person o1, Person o2){ if(o1.name.compareTo(o2.name)==0) return o1.age - o2.age; return o1.name.compareTo(o2.name); } } public class Test{ public static void main(String[] args){ ArrayList<Person> arr = new ArrayList<Person>(); arr.add(new Person("hujunzheng", 22)); arr.add(new Person("caihaibin", 21)); arr.add(new Person("huangweidong", 22)); ArrayList<Student> arr1 = new ArrayList<Student>(); arr1.add(new Student("hujunzheng", 22, 500)); arr1.add(new Student("caihaibin", 21, 444)); arr1.add(new Student("huangweidong", 22, 777)); ArrayList<Worker> arr2 = new ArrayList<Worker>(); arr2.add(new Worker("789", 22, 500)); arr2.add(new Worker("465", 21, 444)); arr2.add(new Worker("798", 22, 777)); //public boolean addAll(Collection<? extends E> c)// 泛型的上限:用于存储的数据 // 如果不是<? extends E> 而只是<E> 那么E的子类型就不能加载进来!因为Collection<Person> 和 ArrayList<Student>泛型管理的不是同一数据类型 // 而 <? extends E> 要求传进来的对象实例管理的泛型只要是 E 或者是 E的子类都行! arr.addAll(arr1); arr.addAll(arr2); Object[] oo = null; Arrays.sort(oo=arr.toArray()); for(Object o : oo) System.out.println(o); //public TreeSet(Comparator<? super E> c); 传递的是比较泛型为 E 或者是 E的父类的比较器 //在进行 E类型两个数据比较的时候, 用 E类 或者 E类型的父类型进行接收,并使用 ?类型的定义的比较方式! System.out.println("泛型上限,下限..................................................."); TreeSet<Worker> tw = new TreeSet<Worker>(new ComparatorPerson());// E 是 Worker, 传递的是其父类Person的比较器 tw.addAll(arr2); for(Iterator it = tw.iterator(); it.hasNext(); ) System.out.println(it.next()); TreeSet<Student> ts= new TreeSet<Student>(new ComparatorPerson());// E 是 Student, 传递的是其父类Person的比较器 ts.addAll(arr1); for(Object o : ts.toArray()) System.out.println(o); //上述的Worker 和 Student在TreeSet中排序时使用的比较器都是Person类实现的比较器 } }