Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solution to compiler warning for generic varargs

A puzzle from this blog. Similar to SO1445233.

Given the following source listing, explain why the compiler is producing a warning at invocation to the list method and give a solution for removing the warning without resorting to @SuppressWarnings annotation.

public class JavaLanguagePuzzle3 {
  public static void main(String[] args) {
    list("1", 2, new BigDecimal("3.5"));
  }  
  private static <T> List<T> list(T... items) {
    return Arrays.asList(items);
  }
}

Warning:

Type safety: A generic array of Object&Serializable&Comparable<?> is created for a varargs parameter
like image 436
TJR Avatar asked Nov 21 '11 01:11

TJR


1 Answers

Change the body of main from list("1", 2, new BigDecimal("3.5")); to JavaLanguagePuzzle3.<Object>list("1", 2, new BigDecimal("3.5"));

Reason: the <> syntax specifies which version of the generic method you want. But, you need to put . in front of it to make the parser happy, and the class name before that for the same reason.

Source: http://codeidol.com/java/javagenerics/Introduction/Generic-Methods-and-Varargs/

like image 112
daveagp Avatar answered Sep 20 '22 04:09

daveagp