Java泛型是什麼
導語:泛型,即“引數化型別”。一提到引數,最熟悉的就是定義方法時有形參,然後呼叫此方法時傳遞實參。那麼引數化型別怎麼理解呢?讓我們瞭解一下吧!
顧名思義,就是將型別由原來的具體的型別引數化,類似於方法中的變數引數,此時型別也定義成引數形式(可以稱之為型別形參),然後在使用/呼叫時傳入具體的型別(型別實參)。
看著好像有點複雜,首先我們看下上面那個例子採用泛型的寫法。
1 public class GenericTest {
2
3 public static void main(String[] args) {
4 /*
5 List list = new ArrayList();
6 ("qqyumidi");
7 ("corn");
8 (100);
9 */
10
11 List
12 ("qqyumidi");
13 ("corn");
14 //(100); // 1 提示編譯錯誤
15
16 for (int i = 0; i < (); i++) {
17 String name = (i); // 2
18 tln("name:" + name);
19 }
20 }
21 }
採用泛型寫法後,在//1處想加入一個Integer型別的物件時會出現編譯錯誤,通過List
結合上面的泛型定義,我們知道在List
1 public interface List
2
3 int size();
4
5 boolean isEmpty();
6
7 boolean contains(Object o);
8
9 Iterator
10
11 Object[] toArray();
12
13
14
15 boolean add(E e);
16
17 boolean remove(Object o);
18
19 boolean containsAll(Collection c);
20
21 boolean addAll(Collection c);
22
23 boolean addAll(int index, Collection c);
24
25 boolean removeAll(Collection c);
26
27 boolean retainAll(Collection c);
28
29 void clear();
30
31 boolean equals(Object o);
32
33 int hashCode();
34
35 E get(int index);
36
37 E set(int index, E element);
38
39 void add(int index, E element);
40
41 E remove(int index);
42
43 int indexOf(Object o);
44
45 int lastIndexOf(Object o);
46
47 ListIterator
48
49 ListIterator
50
51 List
52 }
我們可以看到,在List介面中採用泛型化定義之後,
自然的,ArrayList作為List介面的實現類,其定義形式是:
1 public class ArrayList
2 implements List
3
4 public boolean add(E e) {
5 ensureCapacityInternal(size + 1); // Increments modCount!!
6 elementData[size++] = e;
7 return true;
8 }
9
10 public E get(int index) {
11 rangeCheck(index);
12 checkForComodification();
13 return entData(offset + index);
14 }
15
16 //...省略掉其他具體的定義過程
17
18 }
由此,我們從原始碼角度明白了為什麼//1處加入Integer型別物件編譯錯誤,且//2處get()到的型別直接就是String型別了。