泛型的上限使用
class Demo9
{
public static void main(String[] args)
{
//泛型上限的使用
TreeSet<Student> ts1 = new TreeSet<>();
ts1.add(new Student("lisi",21));
ts1.add(new Student("zhaosi",24));
ts1.add(new Student("wangsi",20));
TreeSet<Worker> ts2 = new TreeSet<>();
ts2.add(new Worker("lisi",22));
ts2.add(new Worker("zhaosi",24));
ts2.add(new Worker("wangsi",28));
// TreeSet<E>
// TreeSet(Collection<? extends E> c)
//假如是Student类,<Studend extends Person>,其父类的对象也是可以存入的
TreeSet<Person> ts = new TreeSet<Person>(ts1);
TreeSet<Person> ts = new TreeSet<Person>(ts2);
System.out.println("Hello World!");
}
}
泛型的下限
import java.util.*;
/*
class ComByName implements Comparator<Student>
{
public int compare(Student stu1,Student stu2)
{
int num = stu1.getName().compareTo(stu2.getName());
return num==0?stu1.getAge()-stu2.getAge():num;
}
}
class ComByName2 implements Comparator<Worker>
{
public int compare(Worker w1,Worker w2)
{
int num = w1.getName().compareTo(w2.getName());
return num==0?w1.getAge()-w2.getAge():num;
}
}*/
class ComByName implements Comparator<Person>
{
public int compare(Person w1,Person w2)
{
int num = w1.getName().compareTo(w2.getName());
return num==0?w1.getAge()-w2.getAge():num;
}
}
class Demo10
{
public static void main(String[] args)
{
TreeSet<E> TreeSet(Comparator<? super E> comparator) Student,Person
//也就是泛型确定都的对象以及其子类对象
ComByName comByName = new ComByName();
TreeSet<Student> ts1 = new TreeSet<>(comByName);
ts1.add(new Student("lisi",21));
ts1.add(new Student("zhaosi",24));
ts1.add(new Student("wangsi",20));
System.out.println(ts1);
TreeSet<E> TreeSet(Comparator<? super E> comparator) Worker,Person
ComByName2 comByName2 = new ComByName2();
TreeSet<Worker> ts2 = new TreeSet<>(comByName);
ts2.add(new Worker("lisi",22));
ts2.add(new Worker("zhaosi",24));
ts2.add(new Worker("wangsi",28));
System.out.println(ts2);
}
}