I have a function foo
which accept a parameter ArrayList<ArrayList<Object>>
. When I tried to call the function by passing a variable with type of ArrayList<ArrayList<Integer>>
, the compiler shows error message that says :
incompatible types:
java.util.ArrayList<java.util.ArrayList<java.lang.Integer>>
cannot be converted into
java.util.ArrayList<java.util.ArrayList<java.lang.Object>>
What should I change/do in order to make the function accept parameter(s) with 2D ArrayList
with any type? Thanks in advance.
Sample code
public static ArrayList<ArrayList<Object>> foo (ArrayList<ArrayList<Object>> parameter)
{
//do something
}
Calling the function
ArrayList<ArrayList<Integer>> parameter;
//do something with the parameter
ArrayList<ArrayList<Integer>> product = foo(parameter);//red line under parameter indicate it has error
Make it generic:
public static <T> ArrayList<ArrayList<T>> foo (ArrayList<ArrayList<T>> parameter) {
//do something
// you probably want to create a new 2D ArrayList somewhere around here
ArrayList<ArrayList<T>> ret = new ArrayList<>();
//do more somethings
}
There are 2 solutions:
1.Use generic (and btw should use List instead of ArrayList)
public static <T> List<List<T>> foo(List<List<T>> parameter) {
//do something
}
public void test() {
List<List<Integer>> parameter;
//do something with the parameter
List<List<Integer>> product = foo(parameter);
}
2.Use nested wildcards:
public static List<? extends List<? extends Object>> foo(List<? extends List<? extends Object>> parameter) {
//do something
}
public void test() {
List<List<Integer>> parameter = new ArrayList<>();
//do something with the parameter
foo(parameter);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.