泛型類,參數放在類名後java
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { ...
泛型方法,參數放在返回值前面dom
import java.io.Closeable; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.List; /** * 非泛型類中定義泛型方法 * @author Administrator * */ public class Method { // 泛型方法,在返回類型前面使用泛型字母 public static <T> void test1(T t){ System.out.println(t); } // T 只能是list 或者list 的子類 public static <T extends List> void test2(T t){ t.add("aa"); } // T... 可變參數 ---> T[] public static <T extends Closeable> void test3(T...a) { for (T temp : a) { try { if (null != temp) { temp.close(); } } catch (Exception e) { e.printStackTrace(); } } } public static void main(String[] args) throws FileNotFoundException { test1("java 是門好語言"); test3(new FileInputStream("a.txt")); } }