gpt4 book ai didi

java - 警告 : [unchecked] unchecked cast while using Generic Array

转载 作者:行者123 更新时间:2023-12-02 11:50:31 30 4
gpt4 key购买 nike

我正在创建我自己的集合类。但一开始,我就受到警告。我在此链接中使用How to create a generic array? 。但我已经收到警告了。

这是我的警告消息:

MySet.java:11: warning: [unchecked] unchecked cast
data = (T[]) new Object[10];
^
required: T[]
found: Object[]
where T is a type-variable:
T extends Object declared in class MySet
1 warning

这是我的初学者代码:

Main.java

public class Main{

public static void main(String[] args){

MySet<Integer> a = new MySet<Integer>();

System.out.printf("empty or not = %d\n",a.empty());

}

}

MySetInterface.java

public interface MySetInterface<T> {
public int empty();
}

MySet.java

public class MySet<T> implements MySetInterface<T>{

private T[] data;
private int used;
private int capacity;

public MySet(){

used = 0;
capacity = 1024;
data = (T[]) new Object[10];
}

public int empty(){

if(used == 0){
return 1;
}
else{
return 0;
}

}

如果我使用

@SuppressWarnings("unchecked")
data = (T[]) new Object[10];

我现在收到此错误消息:

MySet.java:12: error: <identifier> expected
data = (T[]) new Object[10];
^
1 error

最佳答案

如果您阅读了所提供问题的答案,它会非常全面地解释为什么显示警告,并且还提供了有效的解决方法。

The above code have the same implications as explained above. If you notice, the compiler would be giving you an Unchecked Cast Warning there, as you are typecasting to an array of unknown component type. That means, the cast may fail at runtime. For e.g, if you have that code in the above method:

建议的类型安全代码。

public <E> E[] getArray(Class<E> clazz, int size) {
@SuppressWarnings("unchecked")
E[] arr = (E[]) Array.newInstance(clazz, size);

return arr;
}

Explanation is provided in the answer

关于java - 警告 : [unchecked] unchecked cast while using Generic Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47903677/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com