基本类型无法做为类型参数
代码如下:
/** * */ package test.thinkinjava.Generics; import java.util.ArrayList; import java.util.List; /** * @author Luo * */ public class Abc<T> { private List<T> list = new ArrayList<T>(); private T element; @Override public String toString() { return list.toString(); } public void addList(T element) { this.list.add(element); } public T getElement() { return element; } public void setElement(T element) { this.element = element; } public static void main(String[] args) { Abc<String> abcString = new Abc<String>(); abcString.addList("a"); abcString.addList("b"); abcString.addList("c"); abcString.addList("d"); abcString.addList("e"); System.out.println(abcString.toString()); abcString.setElement("okda"); System.out.println(abcString.getElement() instanceof String); Abc<Integer> abcInteger = new Abc<Integer>(); abcInteger.addList(1); abcInteger.addList(2); abcInteger.addList(3); abcInteger.addList(4); abcInteger.addList(5); System.out.println(abcInteger.toString()); abcInteger.setElement(1234567899); System.out.println(abcInteger.getElement() instanceof Integer); } }
上面的T也可以换成其他英文字母
输出结果是