泛型的上限和下限

泛型的上限使用

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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值