Reputation: 1076
I was told to create a method that combine two generic ArrayList
.
Here is the code, and I've several questions:
public static <T> List<T> combineArrayList(List<T> list_Array1, List<T> list_Array2){
List<T> returnList = new ArrayList<T>();
int i;
for(i = 0;i< list_Array1.size();i++){
returnList.add(list_Array1.get(i));
}
for(i = 0;i< list_Array2.size();i++){
returnList.add(list_Array2.get(i));
}
return returnList;
}
public static <T> void main(String[] args) {
// Create a list and add some colors to the list
List<String> list_Strings = new ArrayList<String>();
List<String> list_Strings2 = new ArrayList<String>();
List<T> returnedList = new ArrayList<T>();
list_Strings.add("Red");
list_Strings2.add("yellow");
returnedList = (List<T>) combineArrayList(list_Strings,list_Strings2);
// Print the list
System.out.println(returnedList);
}
static
to the function combineArray()
generic
declaration as <T>
every time when I want to use Generic type in the function?List<String>
how should I declare the variable as List<T>
or List<String>
, what is the convention?combineArrayList()
to List<T>
which his return type is already List<T>
?Thanks!
Upvotes: 0
Views: 59
Reputation: 71
List<T> returnedList = new ArrayList<T>();
as you are specifying a generic type here. Generics are not evaluated at runtime.public static void main(String[] args) {
// Create a list and add some colors to the list
List<String> list_Strings = new ArrayList<>();
List<String> list_Strings2 = new ArrayList<>();
list_Strings.add("Red");
list_Strings2.add("yellow");
List<String> returnedList = combineArrayList(list_Strings, list_Strings2);
// Print the list
System.out.println(returnedList);
}
combineArrayList()
function and you want to assign it to List<T>
.Upvotes: 1