本文介绍了Java的泛型的基本使用。
1. 为什么使用泛型
看下面一个例子:
为了说明问题,本类写的尽量简陋,请把目光主要放在类型上。
/** * @author Xing Xiaoguan (xingrenguanxue) */ public class MyArrayList { private int[] elementData; private int size = 0; public MyArrayList(int capacity) { elementData = new int[capacity]; } //向数组中添加元素 public void add(int i) { if (size == elementData.length) { throw new IndexOutOfBoundsException("数组已满"); } elementData[size++] = i; } //从数组中根据下标获取元素 public int get(int index) { if (index < 0 || index > size - 1) { t<p>本文来源gao!%daima.com搞$代*!码$网9</p>hrow new IndexOutOfBoundsException("超出范围"); } return elementData[index]; } @Override public String toString() { return "MyArrayList{" + "elementData=" + Arrays.toString(elementData) + '}'; } }
该类很简单:有两个成员变量,elementData
是一个数组,size
是数组中元素的数量。add
和get
方法能添加和获取元素。
下面测试一下:
public class Test { public static void main(String[] args) { MyArrayList myArrayList = new MyArrayList(4); myArrayList.add(111); //向数组中添加3个int元素 myArrayList.add(222); myArrayList.add(333); int i = myArrayList.get(0); //获取 System.out.println(i); //以上正常运行 myArrayList.add("行小观"); //添加一个String元素,类型不匹配,报错 } }
向数组中添加3个int
类型的元素并能获取,这没问题。
但是如果我们的场景不再需要int
类型的元素,而是需要String
类型的,那怎么办?
很显然,继续使用该类会报错,报错的原因很简单:我们向数组中添加的元素是String
类型的,而数组和方法参数类型是int
类型。
此时,就得需要再写一份代码,该份代码较之前的并无大修改,只是把int
改为String
。如果场景继续变怎么办?那就再写一份新代码!
这样太麻烦了!有没有解决办法?有!
我们知道,Object
类是所有类的父类,Object
类型的变量能够引用任何类型的对象。所以可以将类型改为Object
:
/** * @author Xing Xiaoguan (xingrenguanxue) */ public class MyArrayList { private Object[] elementData; private int size = 0; public MyArrayList(int capacity) { elementData = new Object[capacity]; } public void add(Object o) { //向数组中添加元素 if (size == elementData.length) { throw new IndexOutOfBoundsException("数组已满"); } elementData[size++] = o; } public Object get(int index) { //从数组中获取元素 if (index < 0 || index > size - 1) { throw new IndexOutOfBoundsException("超出范围"); } return elementData[index]; } @Override public String toString() { return "MyArrayList{" + "elementData=" + Arrays.toString(elementData) + '}'; } }
再测试一下:
public class Test { public static void main(String[] args) { //myArrayList 给int元素使用 MyArrayList myArrayList = new MyArrayList(4); myArrayList.add(111); //向数组中添加3个int元素 myArrayList.add(222); myArrayList.add(333); int i = (int) myArrayList.get(0); //获取 System.out.println(i); //myArrayList 给String元素使用 MyArrayList myArrayList1 = new MyArrayList(4); myArrayList1.add("aaa"); myArrayList1.add("bbb"); myArrayList1.add("ccc"); String str = (String) myArrayList1.get(1); System.out.println(str); } }