java - Array type erasure
问题描述
Why the following code is potentially not type-safe (the compiler generates a warning)?
class ArrayTypeErasure<T> {
private T[] elements;
public void setElements(List<T> elements) {
this.elements = (T[]) elements.toArray();
}
}
I'm trying to think of any situations when the code would fail, but so far it's only me who is failing.
解决方案
Simply because List#toArray()
returns an Object[]
so there is no guarantee from this method that it would return T[]
Now, in practice, it's ok since you always know that it will return the wanted type
You could use @SuppressWarnings("unchecked")
to avoid this warning from appearing
推荐阅读
- azure-eventgrid - 为 Azure 函数创建 EvenGridSubscription 时尝试验证提供的端点失败
- javascript - 无法访问正确的“this”
- javascript - 功能单击在右键单击 li 元素上不起作用
- javascript - node.js 错误:ENOENT:没有这样的文件或目录-使用本地模块时
- azure-ad-b2c - 使用高级设置手动配置 Azure Active Directory B2C
- java - log4j2:父记录器级别低于子记录器
- c# - 如果本地数据库已在应用程序第一次运行时播种,则拉异步不起作用
- docker - 如何在 windows server 2016 docker 容器上启用 websocket
- vue.js - 在嵌套项目列表中显示 VUE 中可拖动项目的计数
- azure-api-management - 自定义身份验证策略