首页 > 解决方案 > 为什么在使用 @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.

标签: javasuppress-warnings

解决方案


@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;

推荐阅读