什么是泛型类?
类似于我们经常使用JDK中的ArrayList<String> list = new ArrayList<String>();就使用的是泛型类,来看看java源码:
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { private static final long serialVersionUID = 8683452581122892189L;
看看他的add方法:
/** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */ public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } /** * Inserts the specified element at the specified position in this * list. Shifts the element currently at that position (if any) and * any subsequent elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws IndexOutOfBoundsException {@inheritDoc} */ public void add(int index, E element) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); ensureCapacityInternal(size + 1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; }
ArrayList在定义时候,就是一个泛型类,它的E代表你要在集合中存放的类型。
泛型的优点:
1、泛型本质上是类型参数化。所谓类型参数化,是指用来声明数据的类型本身,也是可以改变的,他由实际参数来决定。
2、在一般情况下,实际参数决定了形式参数的类型。而类型参数化,则是实际参数的类型决定了形式参数的类型。
我们写个例子看看:
定义泛型类Dao:
public class Dao<T> { public T insert(T t){ return t; } }
类中的T可以是任何的K、V、P随意的字母。
T代表类型,比如Integer,String
使用泛型类:
public class Service { Dao<Student> dao = new Dao<Student>(); public Student insert(Student student){ return dao.insert(student); } }
public class Student {
}
欢迎关注我的微信公众号: