java - 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类型?
解决方案
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);
}
推荐阅读
- c - 如何声明一个char数组**?
- php - PHP回显INF而不是成绩的结果
- c# - UWP ListView 滚动和缩放不起作用
- c - 如何在给定变量作为引用的函数内初始化结构
- python - 在图上使用 Beam Search 生成得分最高的句子
- xslt - 嵌套 XML XSLT 1.0 转换
- c - 我正在尝试编写一个程序,它似乎完全没问题,但我找不到它不起作用的原因,任何帮助将不胜感激
- mysql - 如何在 MySQL 转储文件的一行中提取多个括号之间的文本
- python - 等待协程并将结果分配给协程外部的变量
- ruby-on-rails - 努力让 rails 6 API only 应用程序以我想要的方式运行