'Is there any way for generics themselves to take type parameters in Java?
Let's say I have a function with the following signature:
<T> T f(List<T> a, T b)
Obviously, I can do the following:
List<Integer> list = new ArrayList<Integer>();
int x = 0;
int y = f(list, x);
However, I am not allowed to do this:
List<List<?>> list = new ArrayList<List<?>>();
List<Integer> x = new ArrayList<Integer>();
List<Integer> y = f(list, x);
In that case, what I would want is a signature something like this:
<T, V> T<V> foo(List<T<?>>, T<V> x)
However, there is two problems with this. First of all, Java simply doesn't let me do that, citing Type 'T' does not have type parameters. Secondly, I assume the first scenario I described as possible would no longer be possible.
So, my question is: is there any way to write a function with a signature that allows for both of the above scenarios?
Solution 1:[1]
You can do that. This compiles:
List<List<Integer>> list = new ArrayList<>();
List<Integer> x = new ArrayList<>();
List<Integer> y = f(list, x); // T is List<Integer>
If you want a separate method that handles Lists of T:
<T> List<T> fList(List<List<T>> a, List<T> b)
List<List<Integer>> list = new ArrayList<>();
List<Integer> x = new ArrayList<>();
List<Integer> z = fList(list, x); // T is Integer
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 | Bohemian |
