U
U
UNy2019-05-16 01:34:43
Java
UNy, 2019-05-16 01:34:43

Lambda + Wild Card, working with lists?

I want to merge 2 lists and return a new one without changing them using a lambda expression:

interface  CombineLists{
    List<Number> combine(List<? extends Number> a, List<? extends Number> b);
}

public class SimpleTest {
    public static void main(String[] args) {
        CombineLists concLists = (a, b) -> {
                List<Number> newL = new ArrayList<>();
                newL.addAll(a);
                newL.addAll(b);
            return newL;
        };

        List<Integer> m1 = Arrays.asList(1,2,3,4);

        List<Double> m2 = Arrays.asList(5.0,6.0,7.0,8.0);

        System.out.println(concLists.combine(m1,m2));
        
    }
}

Everything works, but I don't like what I have to duplicate in the parameters? extends Number. Tried replacing with:
interface  CombineLists<T extends Number>{
    List combine(List<T> a, List<T> b);
}

But for some reason it highlights the addition lines: Unchecked assignment: java.util.List' to java.util.Collection ? extends java.lang.Number and the method call string itself: Unchecked call to combine(List, List) as a member of raw type Practice.Lambdas.CombineLists. Although everything works. After all, the values ​​in the list cannot be of any other type than Number and its descendants, so there is no point in checking, then what's the matter? why is ide unhappy? How can you write properly? :)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question