关于Java泛型的类型参数的强制转换?

以下是ArrayList<E>类中一段源码,众所周知此类是泛型类,但是会出现泛型擦除,问题就是return (E) elementData[index]中这个(E)岂不是无用了?

    transient Object[] elementData; // non-private to simplify nested class access
    

    // Positional Access Operations

    @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);
    }
阅读 6.4k
4 个回答
新手上路,请多包涵

有用的,因为前面 elementData 声明为 Object[] 了。

new arraylist的时候 传入 E的具体类型
E是你add的时候传入的 元素类型是E, 数据是存入到 transient Object[] elementData 里面
不强转 的话 类型不匹配会报编译错误。

泛型就是语法糖,用于编译阶段的,如果类型不匹配编译错误,帮助开发者更容易发现问题,跟运行时没什么关系。

没有强转(E),编译不通过啊。
elementDataObject类型,而返回值是E类型。
编译通过后是不需要了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题