4

我的代码在 Java SE 7 中给出了警告。如何在使用注释来抑制警告的情况下绕过它;并按预期使用可变参数:

  import java.util.Iterator;

  public class UnionIterator < E > implements Iterator < E > {

  public static < E > Iterator < E > newInstance (Iterator < E > ... iterators) {
    return new UnionIterator < E >(iterators);
  }

  private Iterator < E > [] iterators;

  private UnionIterator (Iterator < E > ... iterators) {
    this.iterators = iterators;
  }

  @Override
  public boolean hasNext() {
    // TODO
    return false;
  }

  @Override
  public E next() {
    // TODO
    return null;
  }

  @Override
  public void remove() {
    // TODO
  }

}

这是警告:

$ javac UnionIterator.java 
Note: UnionIterator.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
$ javac -Xlint:unchecked UnionIterator.java 
UnionIterator.java:5: warning: [unchecked] Possible heap pollution from parameterized vararg type Iterator<E>
  public static < E > Iterator < E > newInstance (Iterator < E > ... iterators) {
                                                                     ^
  where E is a type-variable:
    E extends Object declared in method <E>newInstance(Iterator<E>...)
UnionIterator.java:11: warning: [unchecked] Possible heap pollution from parameterized vararg type Iterator<E>
  private UnionIterator (Iterator < E > ... iterators) {
                                            ^
  where E is a type-variable:
    E extends Object declared in class UnionIterator
2 warnings
4

1 回答 1

5

你不能。如果您使用的是 Java 7,则可以使用@SafeVarargs工厂方法上的注释来抑制每次调用newInstance.

于 2012-05-12T01:01:29.387 回答