|
1 | 1 | 《《《 [返回首页](../README.md) <br/>
|
2 | 2 | 《《《 [上一节](../Preface.md)
|
3 | 3 |
|
4 |
| - |
5 | 4 | ## 第一章(简介)
|
6 | 5 |
|
7 | 6 | `Java` 最新版本中现在对泛型和集合与许多其他新功能有良好的支持,包括装箱和拆箱,新的循环形式,以及接受可变数量参数的函数。我们从一个例子开始说明了这
|
|
10 | 9 | 因此作为我们的座右铭,让我们做一些简单求和:把三个数字一个列表并将它们加在一起。 下面是如何在 `Java` 中使用泛型:
|
11 | 10 |
|
12 | 11 | ```java
|
13 |
| - List<Integer> ints = Arrays.asList(1,2,3); |
14 |
| - int s = 0; |
15 |
| - for (int n : ints) { s += n; } |
16 |
| - assert s == 6; |
| 12 | + List<Integer> ints = Arrays.asList(1,2,3); |
| 13 | + int s = 0; |
| 14 | + for (int n : ints) { |
| 15 | + s += n; |
| 16 | + } |
| 17 | + assert s == 6; |
17 | 18 | ```
|
18 | 19 |
|
19 | 20 | 不需要太多的解释你就可以读懂代码,但是让我们来看看关键特征。接口列表和类数组是集合框架的一部分(都可以在 `java.util` 包中找到)。类型 `List` 现在是
|
|
25 | 26 | 下面是在泛型之前 `Java` 中相同作用的代码:
|
26 | 27 |
|
27 | 28 | ```java
|
28 |
| - List ints = Arrays.asList( new Integer[] { |
29 |
| - new Integer(1), new Integer(2), new Integer(3) |
30 |
| - } ); |
31 |
| - int s = 0; |
32 |
| - for (Iterator it = ints.iterator(); it.hasNext(); ) { |
| 29 | + List ints = Arrays.asList( new Integer[] { |
| 30 | + new Integer(1), new Integer(2), new Integer(3) |
| 31 | + } ); |
| 32 | + int s = 0; |
| 33 | + for (Iterator it = ints.iterator(); it.hasNext(); ) { |
33 | 34 | int n = ((Integer)it.next()).intValue();
|
34 | 35 | s += n;
|
35 |
| - } |
36 |
| - assert s == 6; |
| 36 | + } |
| 37 | + assert s == 6; |
37 | 38 | ```
|
38 | 39 |
|
39 | 40 | 阅读这段代码并不是那么容易。 没有泛型,就没有办法指出类型声明你打算在列表中存储什么样的元素,所以而不是写 `List<Integer>`,你写 `List`。 现在是
|
|
44 | 45 | 顺便说一句,下面是如何在泛型之前用 `Java` 中的数组做同样的事情:
|
45 | 46 |
|
46 | 47 | ```java
|
47 |
| - int[] ints = new int[] { 1,2,3 }; |
48 |
| - int s = 0; |
49 |
| - for (int i = 0; i < ints.length; i++) { s += ints[i]; } |
50 |
| - assert s == 6; |
| 48 | + int[] ints = new int[] { 1,2,3 }; |
| 49 | + int s = 0; |
| 50 | + for (int i = 0; i < ints.length; i++) { |
| 51 | + s += ints[i]; |
| 52 | + } |
| 53 | + assert s == 6; |
51 | 54 | ```
|
52 | 55 |
|
53 | 56 | 这比使用泛型和集合的相应代码略长,可以说是不太可读,而且肯定不够灵活。 集合让你轻松增大或缩小集合的大小,或在切换到适当的不同的表示形式时,如链表或散
|
|
0 commit comments