Itzik.B
Itzik.B

Reputation: 1076

generic method return type must be also generic?

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);

}
  1. I dont really understand why the compiler want to add static to the function combineArray()
  2. In the main function prototype, I needed to add the generic declaration as <T> every time when I want to use Generic type in the function?
  3. I've created an Generic variable that will have the return data from the function, by far I know it will be return as List<String> how should I declare the variable as List<T> or List<String>, what is the convention?
  4. Why the compiler want me to cast the type of the combineArrayList() to List<T> which his return type is already List<T>?

Thanks!

Upvotes: 0

Views: 59

Answers (1)

Abhishek Chauhan
Abhishek Chauhan

Reputation: 71

  1. Your are calling the function from static context. So it needs to be static or create object of the class.
  2. You are forced to do so because of this line in your code List<T> returnedList = new ArrayList<T>(); as you are specifying a generic type here. Generics are not evaluated at runtime.
  3. You can do something like this,
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);

  }
  1. The compiler does not know what will be returned by your combineArrayList() function and you want to assign it to List<T>.

Upvotes: 1

Related Questions