Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combinig two generic List

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.

like image 532
Krushna Avatar asked Mar 04 '26 02:03

Krushna


1 Answers

Why don't you use addAll ?

   public static <E> List<E> union(List<? extends E> a,List<? extends E> b){
        List<E> es= new ArrayList<E>();
        es.addAll(a);
        es.addAll(b);
        return es;
    }

And use it like this

List<? extends Number> list = union(a, b);
like image 116
NiziL Avatar answered Mar 06 '26 15:03

NiziL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!