A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

本帖最后由 noiary 于 2014-9-25 23:30 编辑
  1. <blockquote><div class="blockcode"><blockquote>import java.util.*;
  2. /*
  3. 泛型限定
  4. */
  5. public class GenericTest2 {

  6.         public static void main(String[] args) {
  7.                 TreeSet<Student> ts = new TreeSet<Student>(new LenComparator());
  8.                 ts.add(new Student("Zhao"));
  9.                 ts.add(new Student("Jiang"));
  10.                 ts.add(new Student("Sun"));
  11.                
  12.                 for(Iterator<Student> it = ts.iterator(); it.hasNext(); )
  13.                         System.out.println(it.next().getName());       

  14.                        
  15.                 TreeSet<Employee> ts2 = new TreeSet<Employee>(new LenComparator());
  16.                 ts2.add(new Employee("iii"));
  17.                 ts2.add(new Employee("uuuuu"));
  18.                 ts2.add(new Employee("yy"));
  19.                
  20.                 for(Iterator<Employee> it = ts2.iterator(); it.hasNext(); )
  21.                         System.out.println(it.next().getName());
  22.                
  23.         }
  24. }

  25. class LenComparator implements Comparator<Person> {

  26.         public int compare(Person p1, Person p2) {
  27.                 int num = new Integer(p1.getName().length()).compareTo(new Integer(p2.getName().length()));
  28.                 if(num == 0)
  29.                         return p1.getName().compareTo(p2.getName());
  30.                 return num;
  31.         }
  32. }

  33. class Person {

  34.         private String name;
  35.        
  36.         public Person(String name) {
  37.                 this.name = name;
  38.         }
  39.        
  40.         public String getName() {
  41.                 return name;
  42.         }
  43. }

  44. class Student extends Person {

  45.         public Student(String name) {
  46.                 super(name);
  47.         }
  48. }

  49. class Employee extends Person {

  50.         Employee(String name) {
  51.                 super(name);
  52.         }
  53. }
复制代码


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马