《Java 核心技术 卷1》 笔记 第12章 泛型程序设计(2)泛型方法完整示例与类型限定
12.3 泛型方法
普通类定义泛型方法如下,需要在返回值前加入 <泛型类型>
❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤
public class Main { public static void main(String[] args) { Integer[] items = new Integer[100]; for(int i = 0; i < 100; i++){ items[i] = i; } System.out.println(ArrayAlg.getMiddle(items)); System.out.println(ArrayAlg.getMiddle(items).getClass().getTypeName()); } } class ArrayAlg{ public static T getMiddle(T[] a){ return a[a.length/2]; }}
❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤
结果:
🚗🚓🚕🛺🚙🚌🚐🚎🚑🚒🚚🚛🚜🚘🚔🚖🚍🦽🦼🛹🚲🛴🛵🏍
🚗🚓🚕🛺🚙🚌🚐🚎🚑🚒🚚🚛🚜🚘🚔🚖🚍🦽🦼🛹🚲🛴🛵🏍
12.4 类型变量的限定
当前的类型T实现了比较器,可以完成比较大小的功能,我们可以通过 来标识这种继承关系:
❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤
public class Main { public static void main(String[] args) { int size = 10; Integer[] items = new Integer[size]; Random r = new Random(); for(int i = 0; i < size; i++){ items[i] = r.nextInt(100); } System.out.println(Arrays.toString(items)); System.out.println(ArrayAlg.min(items)); System.out.println(ArrayAlg.min(items).getClass().getTypeName()); } } class ArrayAlg{ public static T min(T[] a){ if(a == null || a.length == 0) return null; T smallest = a[0]; for(int i = 1; i 0){ smallest = a[i]; } } return smallest; }}
❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤
结果:
🚗🚓🚕🛺🚙🚌🚐🚎🚑🚒🚚🚛🚜🚘🚔🚖🚍🦽🦼🛹🚲🛴🛵🏍
🚗🚓🚕🛺🚙🚌🚐🚎🚑🚒🚚🚛🚜🚘🚔🚖🚍🦽🦼🛹🚲🛴🛵🏍
原文例子(略改动,Pair用了javafx的):
❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤
public class Main { public static void main(String[] args) { GregorianCalendar[] birthdays = { new GregorianCalendar(1906, Calendar.DECEMBER, 9), new GregorianCalendar(1815, Calendar.DECEMBER, 10), new GregorianCalendar(1903, Calendar.DECEMBER, 3), new GregorianCalendar(1910, Calendar.JUNE, 22), }; Pair mm = ArrayAlg.minmax(birthdays); System.out.println("min = " + mm.getKey().getTime()); System.out.println("max = " + mm.getValue().getTime()); } } class ArrayAlg{ public static T min(T[] a){ if(a == null || a.length == 0) return null; T smallest = a[0]; for(int i = 1; i 0){ smallest = a[i]; } } return smallest; } public static Pair minmax(T[] a){ if(a == null || a.length == 0) return null; T min = a[0]; T max = a[0]; for(int i = 1; i 0) min = a[i]; if(max.compareTo(a[i]) < 0) max = a[i]; } return new Pair(min,max); }}
❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤
结果:
🚗🚓🚕🛺🚙🚌🚐🚎🚑🚒🚚🚛🚜🚘🚔🚖🚍🦽🦼🛹🚲🛴🛵🏍
🚗🚓🚕🛺🚙🚌🚐🚎🚑🚒🚚🚛🚜🚘🚔🚖🚍🦽🦼🛹🚲🛴🛵🏍
12.5 泛型代码和虚拟机
虚拟机中没有泛型类,所有对象都属于非泛型类。
Sun编译器编译的 Java 泛型代码,不兼容 5.0 以前的虚拟机
虚拟机在编译过程,会把泛型的类型擦除,替换为原本的Object类型,怎么证明呢?
进入编译后class文件目录
执行命令:
❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤
javap -c Main.class
❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤
别的都不重要,Main 中使用了泛型的只有这一句:
传入参的泛型没了,变成 Comparable
键值对对应类型,都变成了 Object
多个泛型限定:
作者说返回值用了第一个限定名替换,实际观察结果:
都是 Object
相关内容:选择 《Java核心技术 卷1》查找相关笔记
评论🌹点赞👍收藏✨关注👀,是送给作者最好的礼物,愿我们共同学习,一起进步
如果对作者发布的内容感兴趣,可点击下方关注公众号 钰娘娘知识汇总 查看更多作者文章哦!