【Java基础进阶笔记】- Day02 - 第三章 泛型

Java基础进阶笔记 - Day02 - 第三章 泛型

系统:Win10
JDK:1.8.0_121
IDE:IntelliJ IDEA 2017.3.7

3.1 泛型概述

在前面学习集合时,我们都知道集合中是可以存放任意对象的,只要把对象存储到未指定泛型的集合后,那么这时他们都会被提升成Object类型。当我们在取出每一个对象,并且进行相应的操作,这时必须采用类型转换。
代码如下:

public class GenericDemo01 {
    
    
    public static void main(String[] args) {
    
    
        Collection coll = new ArrayList();
        coll.add("abc");
        coll.add(123); // 由于集合没有做任何限制,任何类型都可以存储到里面
        // 使用迭代器遍历集合
        Iterator it = coll.iterator();
        while (it.hasNext()) {
    
    
            String str = (String)it.next();
            System.out.println(str);
            System.out.println(str.length());
        }
    }
}

运行结果:
在这里插入图片描述

可以看到,程序在运行时报错:java.lang.ClassCastException。为什么会发生类型转换异常呢?我们来分析下:由于集合中什么类型的元素都可以存储,导致取出时强制转换引发运行时ClassCastException,怎么解决这个问题呢?Collection虽然可以存储各种对象,但实际通常Collection只存储同一类型对象。例如都是存储字符串对象,因此在JDK1.5之后,新增了 泛型(Generic) 语法,让我们在设计API时可以指定类或方法支持泛型,这样我们在使用API的时候也变得更为简洁,并得到了编译时期的语法检查。

  • 泛型:可以在类或者方法中预支的使用未知的类型

小知识:一般在创建对象时,将未知的类型确定具体的类型。当没有指定泛型时,默认类型为Object类型

3.2 使用泛型的好处

上面我们将泛型进行了引入,那么泛型带来了哪些好处呢?

  • 将运行时期的ClassCastException,转移到了编译时期变成了编译失败
  • 避免了类型强转的麻烦
  • 泛型是什么类型,就只能存储什么类型数据

通过下面一个例子体验一下:

public class GenericDemo02 {
    
    
    public static void main(String[] args) {
    
    
        Collection<String> coll = new ArrayList<>();
        coll.add("abc");
        coll.add("defg");
        // 当集合明确类型后,存放类型不一致就会编译报错
        // coll.add(3); //add (java.lang.String) in Collection cannot be applied to (int)
        // 集合明确具体存放元素的类型,那么在使用迭代器的时候,迭代器也同样会知道具体遍历元素的类型
        Iterator<String> it = coll.iterator();
        while (it.hasNext()) {
    
    
            // 当使用Iterator<String>控制元素类型后,获取的元素就直接是String类型
            String s = it.next();
            System.out.println(s);
            System.out.println(s.length());
        }
    }
}

运行结果:
在这里插入图片描述

小知识:泛型是数据类型的一部分,我们将类名与泛型合并一起看做数据类型

3.3 泛型的定义与使用

我们在集合中会大量使用到泛型,这里来完整的学习泛型知识
泛型,用来灵活的将数据类型应用到不同的类、方法、接口中,将数据类型作为参数进行传递
定义和使用含有泛型的类 - 在创建对象的时候确定泛型
定义格式:

修饰符 class 类名<代表泛型的变量> {
    
    
    // ...
}

例如:API中的ArrayList集合:

public class ArrayList<E> {
    
    
    public boolean add(E e) {
    
    ...}
    public E get(int index) {
    
    ...}
    ...
}

例如:ArrayList list = new ArrayList();
此时,变量E的值就是String类型,那么我们的类型就可以理解为:

public class ArrayList<String> {
    
    
    public boolean add(String e) {
    
    ...}
    public String get(int index) {
    
    ...}
    ...
}

再例如:ArrayList list = new ArrayList();
此时,变量E的值就是Integer类型,那么我们的类型就可以理解为:

public class ArrayList<Integer> {
    
    
    public boolean add(Integere) {
    
    ...}
    public Integer get(int index) {
    
    ...}
    ...
}

举例自定义泛型类:

public class MyGenericClass<T> {
    
    
    // 我们这里将T定义为我们的泛型
    private T name;

    public T getName() {
    
    
        return name;
    }

    public void setName(T name) {
    
    
        this.name = name;
    }
}

使用方式:

public class GenericClassDemo {
    
    
    public static void main(String[] args) {
    
    
        // 创建一个泛型为String的类
        MyGenericClass<String> mgc1 = new MyGenericClass<String>();
        // 调用setName
        mgc1.setName("张三");
        // 调用getName
        String name1 = mgc1.getName();
        System.out.println(name1);
        // 创建一个泛型为Integer的类
        MyGenericClass<Integer> mgc2 = new MyGenericClass<Integer>();
        // 调用setName
        mgc2.setName(123);
        // 调用getName
        Integer name2 = mgc2.getName();
        System.out.println(name2);
    }
}

运行结果:
在这里插入图片描述

含有泛型的方法 - 调用方法时,确定泛型的类型
定义格式:

修饰符 <代表泛型的变量> 返回值类型 方法名(参数) {
    
    
    // ...
}

例如:

public class MyGenericMethod {
    
    
    public <T> void show(T t) {
    
    
        System.out.println(t);
    }

    public <T> T getT(T t) {
    
    
        return t;
    }
}

使用方式:

public class GenericMethodDemo {
    
    
    public static void main(String[] args) {
    
    
        // 创建对象
        MyGenericMethod mgm = new MyGenericMethod();
        // 调用方法
        mgm.show("abc");
        Boolean b = mgm.getT(true);
        mgm.show(b);
    }
}

运行结果:
在这里插入图片描述

含有泛型的接口
定义格式:

修饰符 interface 接口名<代表泛型的变量> {
    
    
    // ...
}

例如:

public interface MyGenericInterface<T> {
    
    
    public abstract void show(T t);

    public abstract T getT(T t);
}

使用方式:
1.定义类时确定泛型的类型
例如:

public class MyImpl01 implements MyGenericInterface<String> {
    
    
    @Override
    public void show(String s) {
    
    
        System.out.println(s);
    }

    @Override
    public String getT(String s) {
    
    
        return s;
    }
}

此时,泛型T的值就是String类型

2.始终不确定泛型,直到创建对象时,确定泛型的类型
例如:

public class MyImpl02<T> implements MyGenericInterface<T> {
    
    
    @Override
    public void show(T t) {
    
    
        System.out.println(t);
    }

    @Override
    public T getT(T t) {
    
    
        return t;
    }
}

使用方式:

public class GenericInterfaceDemo {
    
    
    public static void main(String[] args) {
    
    
        // 创建对象之前泛型已经确定是String
        MyImpl01 my01 = new MyImpl01();
        my01.show("abc");
        String s1 = my01.getT("张三");
        System.out.println(s1);

        // 创建对象时才能确定泛型的类型
        MyImpl02<String> my02 = new MyImpl02<String>();
        my02.show("def");
        String s2 = my02.getT("李四");
        System.out.println(s2);

        MyImpl02<Integer> my03 = new MyImpl02<Integer>();
        my03.show(123);
        Integer s3 = my03.getT(456);
        System.out.println(s3);
    }
}

运行结果:
在这里插入图片描述

3.4 泛型通配符

当使用泛型或者接口时,传递的数据中,泛型类型不确定,可以通过适配符<?>表示,但是一旦使用泛型的通配符后,只能使用Object类中的共性方法,集合中元素自身方法无法使用
通配符基本使用
泛型的通配符:不知道使用什么类型来接收的时候,此时可以使用?,?表示位置通配符
此时只能接收数据,不能往该集合中存储数据
举个例子:

public class GenericDemo03 {
    
    
    public static void main(String[] args) {
    
    
        Collection<String> coll1 = new ArrayList<>();
        coll1.add("张三");
        coll1.add("李四");
        coll1.add("王二");

        Collection<Integer> coll2 = new ArrayList<>();
        coll2.add(1);
        coll2.add(2);
        coll2.add(3);

        showCollection(coll1);
        showCollection(coll2);
    }

    // 写一个方法可以迭代所有类型的Collection集合
    public static void showCollection(Collection<?> coll) {
    
     // ?代表可以接收任意类型
        Iterator<?> it = coll.iterator();
        while (it.hasNext()) {
    
    
            System.out.println(it.next());
        }
    }
}

运行结果:
在这里插入图片描述

小知识:泛型不存在继承关系
下面这样写是错误的:通配符类型“?”无法直接实例化
Collection<?> coll = new ArrayList<?>(); // Wildcard type ‘?’ cannot be instantiated directly

通配符高级使用 - 受限泛型
之前设置泛型的时候,实际上是可以任意设置的,只要是类就可以设置。但是在Java的泛型中可以指定一个泛型的上限或下限
泛型的上限:

  • 格式:类型名称 <? extends 类> 对象名称
  • 意义:只能接收该类型及其子类

泛型的下限:

  • 格式:类型名称 <? super 类型> 对象
  • 意义:只能接收该类型及其父类型

比如:现已知Object类,String类,Number类,Integer类,其中Number是Integer的父类,代码演示如下:

public class GenericDemo04 {
    
    
    public static void main(String[] args) {
    
    
        Collection<Integer> coll1 = new ArrayList<Integer>();
        Collection<String> coll2 = new ArrayList<String>();
        Collection<Number> coll3 = new ArrayList<Number>();
        Collection<Object> coll4 = new ArrayList<Object>();
        
        // 泛型必须是Number或者Number的子类
        showCollection1(coll1);
        showCollection1(coll2); // 错误
        showCollection1(coll3);
        showCollection1(coll4); // 错误
        
        // 泛型必须是Number或者Number的父类
        showCollection2(coll1); // 错误
        showCollection2(coll2); // 错误
        showCollection2(coll3);
        showCollection2(coll4);
    }

    // 泛型的上限:此时的泛型?,必须是Number类型或者Number类型的子类
    public static void showCollection1(Collection<? extends Number> coll) {
    
    }
    // 泛型的下限:此时的泛型?,必须是Number类型或者Number类型的父类
    public static void showCollection2(Collection<? super Number> coll) {
    
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35132089/article/details/111591883
今日推荐