首页 > 解决方案 > ArrayList 的 get() 中的通用性如何

问题描述

我正在尝试开发我的自定义 ArrayList 类,它的工作方式与 java.util.ArrayList 相同。
我可以调整大小和其他事情。我在尝试从我的 ArrayList 中获取我的对象时被卡住了。在调用add(T data)时可以添加。Object[index]但是当我尝试添加时get(index),当时我需要将对象转换为 T 类型。在 java.lang.ArrayList 中,他们没有进行任何类型转换。

有人可以放一些灯吗?

transient Object[] elementData;
E elementData(int arg0) {
   return this.elementData[arg0];
}
public E get(int arg0) {
  this.rangeCheck(arg0);
  return this.elementData(arg0);
}

如何elementData()将Object类型转换为E类型?

标签: javagenerics

解决方案


They certainly do cast elementData[index] to E:

@SuppressWarnings("unchecked")
E elementData(int index) {
    return (E) elementData[index];
}

called by:

/**
 * 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);
}

推荐阅读