Combinig two generic List
collections, generics, java
Solution
change your `List<Number> list3=union(a, b);` to `List<? extends Number> list3=union(a, b);` and that should work
and if i can suggest something, create your list as generic `List<E> es= new ArrayList<E>();`, so you don't have to cast it before return
Problem
I want to union two generic list and want to produce new list , I am providing my code in a simple format. ``` public class Example{ public static <E> List<E> union(List<? extends E> a,List<? extends E> b){ List<Object> es= new ArrayList<Object>(); for( E e:a){ es.add(e); } for( E e:b){ es.add(e); } return (List<E>) es; } public static void main(String[] args) { List<Long> a=new ArrayList<Long>(); a.add(1L); List<Integer> b=new ArrayList<Integer>(); b.add(2); List<Number> list3=union(a, b);//Compilation Error due to mismatch of return type List<String> a1=new ArrayList<String>(); a1.add("H"); List<String> a2=new ArrayList<String>(); a1.add("=E"); List<String> a3=union(a1, a2);//no compilation error } } ``` My requirements is I should able to combine two integer and long list to produce a number list and I should able to combine other type as well. The problem is here is about the return type when I am trying combine the integer and long list. What changes should i need to make to make my code work.