ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] # 泛型 ## 为什么要使用泛型 在之前学过的集合框架中,List和Map都使用了泛型技术来确认其内容的数据类型。 如果不使用泛型,在程序运行阶段,会带来数据类型转型的错误风险。 ~~~ List<String> list = new ArrayList<String>(); list.add("tom"); for (int i = 0; i < list.size(); i++) { String obj = list.get(i); System.out.println(obj); } List list2 = new ArrayList(); list2.add("helen"); list2.add(2); // 自动装箱成Integer list2.add(true); // 自动装箱成Boolean for (int i = 0; i < list2.size(); i++) { String obj = (String)list2.get(i); // 此处是有风险的 } ~~~ 在Java中,使用变量之前,必须要先定义变量的数据类型,存在一种特殊的现象,就是多态(数据类型是父类,实现对象是子类),变量赋值不一定要完全和数据类型一致,可以赋予子类对象给它。 ~~~ public class Client2 { public static void main(String[] args) { Point point = new Point(); point.x = "东经102°"; point.y = "北纬32°"; point.x = 102; point.y = 32; String s = (String) point.x; point.print(); } } class Point { Object x; Object y; public void print() { System.out.println(x + "" + y); } } ~~~ > 向下转型会带来数据风险的(ClassCastException) ## 泛型使用 ~~~ public class Client3 { public static void main(String[] args) { Point3<Integer, Integer> p3 = new Point3<Integer, Integer>(); p3.x = 1; p3.x = 2; } } class Point3<T1, T2> { T1 x; T2 y; } ~~~ **泛型定义**:名字要符合标识符定义的规范,但是我们一般使用大写字母定义,T(一般的泛型类型) E(异常的泛型类型) K V (键值对的泛型类型) 类的泛型在className之后定义,只有定义的泛型类型才能在类中使用。 > 泛型一般使用于框架设计,在实际的应用开发中较少运行。