Jdk1.5以后出现的新特性,用于解决安全问题,是一个安全机制;
好处1:将运行时出现的异常ClassCastException,转移到了编译时期;
方便于程序员解决问题,让运行时期问题减少,更加安全
好处2:避免了强制转换的麻烦
Comparable接口以及comparator接口就体现了泛型的应用
什么时候定义泛型类?
当类中要操作的引用数据类型不确定的时候,
早期定义Object来完成扩展,现在定义泛型来完成扩展
将运行时的异常转移到编译时期
泛型类定义的泛型,在整个类中有效,如果被方法调用,
那么泛型类的对象明确要操作的具体类型后,所有要操作的类型就已经固定了。
为了让不同方法可以操作不同的类型,而且类型还不确定。
那么可以将泛型定义在方法上。
泛型类泛型与泛型方法泛型可以同时存在
静态方法不可以访问类上定义的泛型,因为要先new对象才有泛型;
如果静态方法操作的引用数据类型不确定,那么可以将泛型定义在方法上。
一种是实现泛型接口的时候就指定具体引用数据类型;
另一种是实现泛型接口的时候仍然不指定引用数据类型,在使用接口实现类的时候在指定泛型的具体数据类型
相关代码如下
package com.javaxl; import java.util.ArrayList; import java.util.Iterator; /** * @author 小李飞刀 * @site www.javaxl.com * @company * @create 2019-05-13 22:19 */ public class GenericDemo { public static void main(String[] args) { // method_1(args); method_3(args); } /** * 概论及使用 * java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String * * 1、泛型指定将运行时的问题转到编译期 * 2、避免了强制转换的麻烦 * @param args */ public static void method_1(String[] args) { ArrayList al = new ArrayList(); al.add("java01"); al.add("java01"); al.add(3); Iterator it = al.iterator(); while (it.hasNext()){ String s = (String) it.next(); System.out.println(s.length()); } } /** * 泛型类的应用 * @param args */ public static void method_2(String[] args){ // GenericDemo_Tool tool = new GenericDemo_Tool(); // tool.setObj(new GenericDemo_Student()); // GenericDemo_Student obj = (GenericDemo_Student) tool.getObj(); GenericDemo_Utils<GenericDemo_Student> tool = new GenericDemo_Utils<GenericDemo_Student>(); tool.setObj(new GenericDemo_Student()); GenericDemo_Student obj = tool.getObj(); } /** * read方法传参只能是String * show方法传参可以是任意类型 * write方法传参可以是任意类型 * @param args */ public static void method_3(String[] args){ GenericDemo_All<String> all = new GenericDemo_All<String>(); all.read("222"); // all.read(222); all.show("333"); all.show(123); GenericDemo_All.write("66666"); GenericDemo_All.write(88888); } } class GenericDemo_Student{ } class GenericDemo_Worker{ } //早期泛型没有出现的时候,为了程序的拓展性,只能用Object, // jdk api中java.lang.Object的equals方法参数就是Object,这也是为了扩展性的问题 class GenericDemo_Tool{ private Object student; public Object getObj() { return student; } public void setObj(Object student) { this.student = student; } } //泛型出来了以后 class GenericDemo_Utils<T>{ private T student; public T getObj() { return student; } public void setObj(T student) { this.student = student; } } /** * 包含了泛型类、泛型方法、静态方法泛型 * @param <T> */ class GenericDemo_All<T>{ public void read(T t){ System.out.println("I read " + t); } public <W> void show(W w){ System.out.println("I show " + w); } public static <E> void write(E e){ System.out.println("I write " + e); } } interface MyInter<T>{ public void read(T t); } class MyInterImpl1 implements MyInter<String>{ @Override public void read(String s) { } } class MyInterImpl2<T> implements MyInter<T>{ @Override public void read(T t) { } }
备案号:湘ICP备19000029号
Copyright © 2018-2019 javaxl晓码阁 版权所有