necromancer
necromancer

Reputation: 24641

Varargs of Non-Reifiable Types in Java SE 7 - how?

My code gives a warning in Java SE 7. How do I get around it without using annotations to suppress warnings; and with varargs as intended:

  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
  }

}

Here is the warning:

$ 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

Upvotes: 4

Views: 712

Answers (1)

Jeffrey
Jeffrey

Reputation: 44808

You cannot. If you are using Java 7, you can use the @SafeVarargs annotation on the factory method to suppress the warning for every invocation of newInstance.

Upvotes: 5

Related Questions