这是我了解到Java泛型擦除之后一直以来的疑惑,但是今天复习的时候突然想到这个问题。
原因是在容器的插入操作之前会有一个检查类型的函数,在获取操作之后会有类型强制转换的操作。
拿ArrayList举例
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
--------------------------------------------------------------------------------
/**
* Ensures that this collection contains the specified element (optional
* operation). Returns <tt>true</tt> if this collection changed as a
* result of the call. (Returns <tt>false</tt> if this collection does
* not permit duplicates and already contains the specified element.)<p>
*
* Collections that support this operation may place limitations on what
* elements may be added to this collection. In particular, some
* collections will refuse to add <tt>null</tt> elements, and others will
* impose restrictions on the type of elements that may be added.
* Collection classes should clearly specify in their documentation any
* restrictions on what elements may be added.<p>
*
* If a collection refuses to add a particular element for any reason
* other than that it already contains the element, it <i>must</i> throw
* an exception (rather than returning <tt>false</tt>). This preserves
* the invariant that a collection always contains the specified element
* after this call returns.
*
* @param e element whose presence in this collection is to be ensured
* @return <tt>true</tt> if this collection changed as a result of the
* call
* @throws UnsupportedOperationException if the <tt>add</tt> operation
* is not supported by this collection
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this collection
* @throws NullPointerException if the specified element is null and this
* collection does not permit null elements
* @throws IllegalArgumentException if some property of the element
* prevents it from being added to this collection
* @throws IllegalStateException if the element cannot be added at this
* time due to insertion restrictions
*/
boolean add(E e);
从源码可以看出,在get()操作里有个强制转换的操作,在add()操作里,在编译前会进行类型检查,用注解@throws ClassCastException进行检查
但是在《java编程思想》(第四版)说到
对进入set()的类型进行检查是不需要的,因为这将由编译器执行。(举的例子中,set()执行了一个保存值的过程)
也就是在编译期间会进行检查。
而对于从get()返回的值进行转型仍旧是需要的,但是.....此处它将由编译器自动插入
没理解错的话就是转型会自己进行,但是源码里面也写了强制转换。不知道是不是为了表达的更清楚才这样。