我是靠谱客的博主 温暖外套,这篇文章主要介绍JavaSE总结笔记 - Generic泛型机制Generic泛型,现在分享给大家,希望可以做个参考。

零基础学Java,肝了bilibili的6百多集JavaSE教程传送门的学习笔记!!!


Generic泛型

一、引言

JDK5.0之后推出的新特性:泛型

泛型这种语法机制,只在程序编译阶段起作用,只是给编译器参考的。(运行阶段泛型没用)

使用泛型的好处:

1、集合中存储的元素类型统一了。

2、从集合中取出的元素类型是泛型指定的类型,不需要进行大量的"向下转型".

使用泛型的缺点:

导致集合存储的元素缺乏多样性


二、案例代码介绍

GenericTest01.java:泛型的优点

GenericTest02.java:自动类型推断机制(又称为钻石表达式):

GenericTest03.java:自定义泛型

1、GenericTest01.java

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
public class GenericTest01 { public static void main(String[] args) { // 不使用泛型机制,分析程序存在缺点。 List myList = new ArrayList(); // 准备对象 Cat c = new Cat(); Bird b = new Bird(); // 将对象添加到集合当中 myList.add(c); myList.add(b); // 遍历集合,取出每个Animal,让它move。 Iterator iterator = myList.iterator(); while (iterator.hasNext()) { // Animal a = iterable.next(); Object next = iterator.next(); // next中没有move方法,无法调用,需要向下转型! if(next instanceof Animal) { Animal animal = (Animal) next; animal.move(); } } // 使用泛型机制 // 使用泛型List<Animal>之后,表示List集合中只允许存储Animal类型的数据。 // 用泛型来指定集合中存储的数据类型。 List<Animal> animalList = new ArrayList<Animal>(); // 使用了泛型之后,集合中元素的数据类型更加统一了。 Cat c2 = new Cat(); Bird b2 = new Bird(); animalList.add(c2); animalList.add(b2); // 获取迭代器 Iterator<Animal> iterator2 = animalList.iterator(); while (iterator2.hasNext()) { // 使用泛型之后每一次迭代之后返回的数据都是Animal类型。 Animal next = iterator2.next(); // 这里不需要再像上面那样强制类型转换了。直接调用。 next.move(); // 调用子类型特有的方法还是要向下转型的。 if (next instanceof Cat) { Cat c3 = (Cat) next; c3.catchMouse(); } if (next instanceof Bird) { Bird b3 = (Bird) next; b3.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("鸟儿在飞翔!"); } }

2、GenericTest02.java

复制代码
1
2
3
4
5
6
7
8
9
10
11
package idea.generics; import java.util.ArrayList; import java.util.List; public class GenericTest02 { public static void main(String[] args) { // ArrayList<"这里的类型会自动推断,不用写">(),前提是JDK8之后才允许。 // 自动类型推断,钻石表达式! List<Animal> animalList = new ArrayList<>(); } }

3、GenericTest03.java

自定义泛型:

自定义泛型的时候,<>尖括号里面内容的是一个标识符,随便写

当你自定义泛型后,可以不用。不用就默认为Object类。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package idea.generics; public class GenericTest03<标识符随便写> { public void doSome(标识符随便写 clz) { } public static void main(String[] args) { // new对象的时候指定了泛型是:String类型 GenericTest03<String> gt = new GenericTest03<>(); // 类型不匹配 // gt.doSome(100); gt.doSome("abc"); } }

最后

以上就是温暖外套最近收集整理的关于JavaSE总结笔记 - Generic泛型机制Generic泛型的全部内容,更多相关JavaSE总结笔记内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(86)

评论列表共有 0 条评论

立即
投稿
返回
顶部