java - 为什么在使用 @SuppressWarnings("unchecked") 时仍然会收到警告?
问题描述
class Lenkeliste<T> implements Liste<T>{
@SuppressWarnings({"unchecked"})
private int iBruk = 0;
private T[] liste = (T[]) new Object[10];
public int stoerrelse(){
return iBruk;
}
public void leggTil(int pos, T x) {
if (pos < 0 || pos >= iBruk) {
throw new UgyldigListeIndeks(pos);
}
if (iBruk == liste.lenght) {
@SuppressWarnings({"unchecked"})
T[] ny = (T[]) new Object[2*iBruk];
for (int i = pos; i < iBruk; i++) {
ny[i] = liste[i];
liste = ny;
liste[i+1] = liste[i];
}
liste[pos] = x;
iBruk++;
}
}
public void leggTil(T x) {
if (iBruk == liste.lenght) {
@SuppressWarnings({"unchecked"})
T[] ny = (T[]) new Object[2*iBruk];
for (int i = 0; i < iBruk; i++) {
ny[i] = liste[i];
liste = ny;
}
liste[iBruk] = x;
iBruk++;
}
}
public void sett(int pos, T x) {
if (pos < 0 || pos >= iBruk) {
throw new UgyldigListeIndeks(pos);
}
liste[pos] = x;
}
public T hent(int pos) {
if (pos < 0 || pos >= iBruk) {
throw new UgyldigListeIndeks(pos);
}
return liste[pos];
}
public T fjern(int pos) {
if (pos < 0 || pos >= iBruk) {
throw new UgyldigListeIndeks(pos);
}
T bort = liste[pos];
for (int i = pos+1; i < iBruk; i++) {
liste[i-1] = liste[i];
}
iBruk--;
return bort;
}
public T fjern() {
T ut = liste[0];
for (int i = 1; i < iBruk; i++) {
liste[i-1] = liste[i];
}
iBruk--;
return ut;
}
}
这是我的代码。老师使用了类似的代码并让它工作,但我仍然收到警告。这是我得到的错误:
Lenkeliste.java:15: error: cannot find symbol
if (iBruk == liste.lenght) {
^
symbol: variable lenght
location: variable liste of type T[]
where T is a type-variable:
T extends Object declared in class Lenkeliste
Lenkeliste.java:28: error: cannot find symbol
if (iBruk == liste.lenght) {
^
symbol: variable lenght
location: variable liste of type T[]
where T is a type-variable:
T extends Object declared in class Lenkeliste
Note: Lenkeliste.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
解决方案
@SuppressWarnings({"unchecked"})
private int iBruk = 0;
private T[] liste = (T[]) new Object[10];
SuppressWarnings
应用于 的声明,而int
不是T[]
.
将抑制放在第二个声明上。
private int iBruk = 0;
@SuppressWarnings({"unchecked"})
private T[] liste = (T[]) new Object[10];
另外,请注意方法中的liste = ny;
行leggTil
不应该在循环内。如果是,您将仅在覆盖之前将数组的第一个元素复制到新数组liste
,因此后续迭代只会将数组元素设置为其当前值(即 null)。
for (int i = 0; i < iBruk; i++) {
ny[i] = liste[i];
}
liste = ny;
推荐阅读
- php - 如何使用 Walker 类为 Wordpress 子菜单导航项生成自定义 ID?
- firebase - 有人能告诉我如何把它变成一个 listview.builder 并且仍然连接到 firebase 吗?顺便说一句,我收藏的名字是“杂货”
- android - Synchronize coroutine from incoming messages
- python - 为什么无法在 django 中导入模型(很可能是由于循环导入)?
- amazon-web-services - Lambda boto3 函数用于验证是否创建了云跟踪
- mysql - SQLite 中是否可以进行十进制数约束?
- java - 如何在 Java 中轻松实现 Matlab 百分位数?
- typescript - 如何为猫鼬类型属性提供自定义类型?
- python - 以 COO 格式构建图连接矩阵
- vba - 使用整数作为自动筛选条件