黑马程序员技术交流社区
标题:
泛型限定小例子
[打印本页]
作者:
l6781155
时间:
2015-7-7 10:14
标题:
泛型限定小例子
package com.mytest;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class test02 {
public static void main(String[] args) {
TreeSet<Student> t1 = new TreeSet<Student>(new Comp());
t1.add(new Student("s02"));
t1.add(new Student("s03"));
t1.add(new Student("s01"));
Iterator<Student> i1 = t1.iterator();
while(i1.hasNext()) {
System.out.println(i1.next().getName());
}
TreeSet<Worker> t2 = new TreeSet<Worker>(new Comp() {
});
t2.add(new Worker("w-----01"));
t2.add(new Worker("w-----03"));
t2.add(new Worker("w-----02"));
Iterator<Worker> i2 = t2.iterator();
while(i2.hasNext()) {
System.out.println(i2.next().getName());
}
}
}
class Comp implements Comparator<Person> {
public int compare(Person p1, Person p2) {
return p1.getName().compareTo(p2.getName());
}
}
class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Student extends Person {
public Student(String name) {
super(name);
}
}
class Worker extends Person {
public Worker(String name) {
super(name);
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2