Java进阶:泛型

泛型

/**
 * 泛型:JDK5.0之后推出的新特性
 * 泛型这种语法机制,只在编译阶段起作用,只是给编译器参考的
 * 使用泛型的好处:
 *      1.集合中存储的元素统一
 *      2.从集合中取出的元素类型是泛型指定的类型,不需要进行大量的“向下转型”
 * 泛型的缺点:
 *      导致集合中存储的元素缺乏多样性
 */
public class GenericTest {
    public static void main(String[] args) {
        // 不使用泛型机制,分析程序存在缺点
        /*List myList = new ArrayList();

        // 准备对象
        Cat cat = new Cat();
        Bird bird = new Bird();

        // 将对象添加到集合中
        myList.add(cat);
        myList.add(bird);

        // 遍历集合,取出Cat让它抓老鼠,取出Bird让它飞
        Iterator iterator = myList.iterator();  //拿到迭代器
        while (iterator.hasNext()) {
            Object obj = iterator.next();
            if (obj instanceof Cat) {
                Cat c = (Cat)obj;
                c.catchMouse();
            }
            if (obj instanceof Bird) {
                Bird b = (Bird)obj;
                b.fly();
            }
            if (obj instanceof Animal) {
                Animal a = (Animal)obj;
                a.move();
            }
        }*/

        // 使用泛型机制来指定集合中存储的数据类型
        // 使用泛型List<Animal>后,表示List集合中只能存储Animal类型的数据
        //List<Animal> myList = new ArrayList<Animal>();

        // JDK8之后引入了:自动类型推断机制(又称:钻石表达式)
        // new ArrayList<这里的类型会自动推断>();
        List<Animal> myList = new ArrayList<>();

        // 准备对象
        Cat cat = new Cat();
        Bird bird = new Bird();

        // 将对象添加到集合中
        myList.add(cat);
        myList.add(bird);

        // 获取迭代器
        Iterator<Animal> iterator = myList.iterator();
        while (iterator.hasNext()) {
            // 使用泛型后,每一次迭代返回的数据都是Animal类型
            Animal a = iterator.next();
            a.move();
            if (a instanceof Cat) {
                Cat c = (Cat)a;
                c.catchMouse();
            }
            if (a instanceof Bird) {
                Bird b = (Bird)a;
                b.fly();
            }
        }

    }
}

class Animal {
    public void move() {
        System.out.println("动物在移动!");
    }
}

class Cat extends Animal {
    public void catchMouse() {
        System.out.println("猫抓老鼠!");
    }
}

class Bird extends Animal {
    public void fly() {
        System.out.println("鸟在飞翔!");
    }
}

自定义泛型

/**
 * 自定义泛型: <>里的是一个标识符,可以随便写
 * Java源代码中经常出现的是<E>和<T>
 *     E是Element单词首字母
 *     T是Type单词首字母
 */
public class GenericTest01<标识符随便写> {
    public void doSome(标识符随便写 o){
        System.out.println(o);
    }
    public static void main(String[] args) {
        GenericTest01<String> gt = new GenericTest01<>();
        // 类型不匹配
        //gt.doSome(100);
        gt.doSome("abc");

        GenericTest01<Integer> gt1 = new GenericTest01<>();
        gt1.doSome(100);
        // 类型不匹配
        //gt1.doSome("abc");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值