Saturday, November 19, 2011

Java Language Puzzle 3

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

6 comments:

Brendan said...

Remove the Generic Type <T>, and replace with a common supertype - in this case it would have to be "Object":

private static List<Object> list(Object... items )
{
return Arrays.asList( items );
}

Ed Merks said...

You should choose a type. I'm not sure you can do that without class qualification:

JavaLanguagePuzzle3.<Object>list( "1", 2, new BigDecimal( "3.5" ) );

You can choose any common super type this way.

Anonymous said...

public static void main( String[] args )
{
Object[] items = new Object[]{"1", 2, new BigDecimal( "3.5")};
list( items );
}

private static List list( T... items )
{
return Arrays.asList( items );
}

Unknown said...

Casting one of the arguments to a "lowest common denominator", such as (Object) "1", or (Serializable) 2 eliminates the warning.

Interestingly, the JavaC compiler does not emit a warning on the given code. Compiler bug? Language ambiguity?

shamaz said...

Just cast one of the 3 arguments to Object, Serializable or Comparable.

The warning means something like 'I can't figure the type of T between these 3 possibilities'.

Srishti Dubey said...

informative read.. I'm all new to JAVA developer community and so was looking around stuff that may acquaint me with JAVA programming. I'm enrolled in http://www.wiziq.com/course/1617-core-java-for-beginners-icse-students and people out there asked me to surf around that may help in visualizing a larger picture worldwide.