Java 泛型机制允许程序员在编译时检验到非法的类型
Java 泛型(generics)是 JDK 5 中引入的一个新特性, 泛型提供了编译时类型安全检测机制,该机制允许程序员在编译时检测到非法的类型。 简单理解就是:泛型指定编译时的类型,减少运行时由于对象类型不匹配引发的异常。其主要用途是提高我们的代码的复用率。 我们Java标准库中的ArrayList就是泛型使用的典型应用: public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
......
public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // replace with empty array. this.elementData = EMPTY_ELEMENTDATA; } }
public void sort(Comparator<? super E> c) { final int expectedModCount = modCount; Arrays.sort((E[]) elementData, 0, size, c); if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } modCount++; }
.....
public E get(int index) { rangeCheck(index);
return elementData(index); }
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; }
} 源码中,ArrayList中的E称为类型参数变量,而整个ArrayList我们称为泛型类型。 我们可以指定除基本类型之外的任何类型,如:ArrayList。 源码中Collection 中? 通配符类型 表示类型的上界,表示参数化类型的可能是T 或是 T的子类。 源码中Comparator 表示类型下界(Java Core中叫超类型限定),表示参数化类型是此类型的超类型(父类型),直至Object。 (编辑:晋中站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |