Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird generics issue

Does anyone know why the following code does not compile and during compilation I get incompatible types exception ?

public class Test<T> {

public static void main(String[] args)
{
    // using Test<?> solves the compilation error
    Test test = new Test();

    // getting error incompatible types:
    // found   : java.lang.Object
    // required: java.lang.Integer
    Integer number = test.getDays().get(0);
}


private List<Integer> getDays() {
    return new ArrayList<Integer>();
}

}

and why using Test with the unbounded wildcard solves this ? I'm using java version 1.6.0_12

like image 592
Amir Hadadi Avatar asked Jun 28 '10 13:06

Amir Hadadi


3 Answers

I am interpreting the question as why doesn't test.getDays() return List<Integer> when the return type is not dependent on the type parameter, T?

When you create a variable that is a raw reference to an instance of Test the compiler drops all generics for access via that variable (for backwards compatibility).

Because test doesn't have its type <T> specified this also means that the <Integer> for getDays is discarded.

like image 139
mikej Avatar answered Nov 07 '22 05:11

mikej


Slight difference from Adel's answer, but did you mean this?

public class Test<T> {

public static void main(String[] args)
{
    Test<Integer> test = new Test<Integer>();

    Integer number = test.getDays().get(0);
}


private List<T> getDays() {
    return new ArrayList<T>();
}

} 
like image 3
Dean J Avatar answered Nov 07 '22 05:11

Dean J


Try this:

public class Test<T> {

public static void main(String[] args)
{
    // using Test<?> solves the compilation error
    Test<Integer> test = new Test<Integer>();

    // getting error incompatible types:
    // found   : java.lang.Object
    // required: java.lang.Integer
    Integer number = test.getDays().get(0);
}


private List<Integer> getDays() {
    return new ArrayList<Integer>();
}

} 
like image 1
Adel Hazzah Avatar answered Nov 07 '22 06:11

Adel Hazzah