'Type T parameters not the same [duplicate]
I have the following code:
public static <T> T print(T element1, T element2){
System.out.println(element1.getClass());
System.out.println(element2.getClass());
return null;
}
public static void main(String[] args) {
print(10, "str");
}
It compiles, no errors. Method "print" accepts two arguments of the same Type (T). But I can call this method, for example, with Integer and String arguments.
If I want to use return value, code doesn't compile:
Integer t = print(10, 20.0); //compilation error
This example also has the same behavior. I can use different types for Array and for Element (but if I use different types, I get ArrayStoreException).
public static <T> void fillArray(T[] array, T element){}
And if I work with Collections, I can't use different types. The following example doesnt compile:
public static <T> void fillList(List<T> list, T element){}
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
fillList(list, 20.0);
}
What's the reason of such behavior? Why I can call method with different types with Arrays, and cannot with Lists, if I declared, that I have only the same type T?
Solution 1:[1]
Where it works, you didn't specify the return type, so the compiler can use the most generic one (Object).
As soon as you declare the return type (that has to be the same as the type of the passed parameters), you cannot mix.
Actually you also don't mix at the place where it works, the compiler just uses Object everywhere.
Solution 2:[2]
It works even when you use the return value, but you have to specify the correct return type, i.e. the type which is common to both parameters. Integer and String both share the supertype Object, and as such they can be considered to be of "same type". Object is the common base type of all other types. For numbers, Number could work as well:
Number t = print(10, 20.0);
Object o = print("string", 12.3);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cyberbrain |
| Solution 2 | knittl |
