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
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.
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>();
}
}
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>();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With