本帖最后由 noiary 于 2014-9-25 23:30 编辑
- <blockquote><div class="blockcode"><blockquote>import java.util.*;
- /*
- 泛型限定
- */
- public class GenericTest2 {
- public static void main(String[] args) {
- TreeSet<Student> ts = new TreeSet<Student>(new LenComparator());
- ts.add(new Student("Zhao"));
- ts.add(new Student("Jiang"));
- ts.add(new Student("Sun"));
-
- for(Iterator<Student> it = ts.iterator(); it.hasNext(); )
- System.out.println(it.next().getName());
-
- TreeSet<Employee> ts2 = new TreeSet<Employee>(new LenComparator());
- ts2.add(new Employee("iii"));
- ts2.add(new Employee("uuuuu"));
- ts2.add(new Employee("yy"));
-
- for(Iterator<Employee> it = ts2.iterator(); it.hasNext(); )
- System.out.println(it.next().getName());
-
- }
- }
- class LenComparator implements Comparator<Person> {
- public int compare(Person p1, Person p2) {
- int num = new Integer(p1.getName().length()).compareTo(new Integer(p2.getName().length()));
- if(num == 0)
- return p1.getName().compareTo(p2.getName());
- return num;
- }
- }
- class Person {
- private String name;
-
- public Person(String name) {
- this.name = name;
- }
-
- public String getName() {
- return name;
- }
- }
- class Student extends Person {
- public Student(String name) {
- super(name);
- }
- }
- class Employee extends Person {
- Employee(String name) {
- super(name);
- }
- }
复制代码
|
|