未经检查的强制转换泛型
在我的代码中我有 <代码> 私有 E[] arrCirc; 在我的构造函数中,我有 arrCirc = (E[]) new Object[capacity];
但是当我尝试编译它时,我收到警告:
[unchecked] unchecked cast
发现:java.lang.Object
必需:E[]
错误,我不知道为什么。
public class Array12<E> implements LimCapList<E>{
private int size = 0;
private int capacity = 0;
private int front;
private int back;
private E[] arrCirc;
public Array12(int capacity){
if( capacity <= 0)
throw new IllegalArgumentException();
arrCirc = (E[]) new Object[capacity];
front = 0;
back = 1;
}
In my code I have
private E[] arrCirc;
and in my constructor I have arrCirc = (E[]) new Object[capacity];
but when I try to compile it I get an warning:
[unchecked] unchecked cast
found : java.lang.Object
required: E[]
Error and I'm not sure why.
public class Array12<E> implements LimCapList<E>{
private int size = 0;
private int capacity = 0;
private int front;
private int back;
private E[] arrCirc;
public Array12(int capacity){
if( capacity <= 0)
throw new IllegalArgumentException();
arrCirc = (E[]) new Object[capacity];
front = 0;
back = 1;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你能让你的
arrCirc
类型为Object[]
(像大多数openJDK 中的通用集合 吗)?(并执行
arrCirc = new Object[capacity];
)否则对于警告,您可以使用 SupressWarning。
Can you make your
arrCirc
of typeObject[]
(like most generic collections in openJDK do) ?( and do
arrCirc = new Object[capacity];
)Otherwise for the warning, you can just use SupressWarning.
Java 使用类型擦除来实现泛型,因此它无法在运行时知道您对 (E[]) 的含义,这就是为什么您会收到潜在不安全强制转换的警告。
看一下 Sun(呃……Oracle)文档: http:// /download.oracle.com/javase/tutorial/java/generics/erasure.html
您始终可以使用
@SuppressWarnings(value = "unchecked")
使警告消失。Java uses Type Erasure to implement generics, so it can't know at Runtime what you mean with (E[]), that's why you get the warning of a potentially unsafe cast.
Take a look at Sun (erm... Oracle) documentation: http://download.oracle.com/javase/tutorial/java/generics/erasure.html
You can always use
@SuppressWarnings(value = "unchecked")
to make the warning go away.