---
title: "使用范型"
author: "hongan"
date: "2008-12-19T21:31:45Z"
tags: ["C", "C#", "C++"]
slug: "untitled"
draft: false
lastmod: "2008-12-19T21:31:45Z"
id: 297774
url: "https://hongan.iteye.com/blog/297774"
---

范型的作用：类型安全检查，不用对集合中的对象进行手动类型转换。

1.Generics类  
public class ArrayList&lt;E&gt; extends AbstractList&lt;E&gt; {   
 // details omitted   
 public void add(E element) {  
    // details omitted5   
 }   
 public Iterator&lt;E&gt; iterator() {    
    // details omitted8   
 }  
}

用String绑定在E上,当我们用add(E element)方法向ArrayList中增加对象时, 那么就像下面的写法一样： public void add(String element)；因为在ArrayList所有方法都会用String来替代E,无论是方法的参数还是返回值。

public class C1&lt;T extends Number&gt; { }  
public class C2&lt;T extends Person & Comparable&gt; { }  
第一个T变量必须继承Number，第二个T必须继承Person和实现Comparable

2.Generics方法  
public &lt;T extends Comparable&gt; T max(T t1, T t2) {  
  if (t1.compareTo(t2) &gt; 0)  
     return t1;  
  else return t2;  
}

max方法的参数类型为单一的T类型，而T类型继承了Comparable，max的参数和返回值都有相同的超类。

Integer iresult = max(new Integer(100), new Integer(200));  
String sresult = max("AA", "BB");  
Number nresult = max(new Integer(100), "AAA"); // does not compile

 

3.通配符  
(1)使用？通配符，匹配所用的类类型  
void printCollection(Collection&lt;?&gt; c) {  
 for (Object e : c) {  
   System.out.println(e);  
 }  
}

(2)有界通配符： &lt;T extends Number&gt;(上界,Number，Number及其子类) &lt;T super Number&gt;(下界Number及其父类)