黑马程序员技术交流社区
标题:
泛型是有些迷糊.. 其实原理赶脚很容易理解,但应用取来好...
[打印本页]
作者:
noiary
时间:
2014-9-25 23:17
标题:
泛型是有些迷糊.. 其实原理赶脚很容易理解,但应用取来好...
本帖最后由 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);
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2