Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difficulty working with subList when using a list of lists

Tags:

java

list

public List<List<Integer>> splitList(
        List<Integer> values) {


    List<List<Integer>> newList = new ArrayList<ArrayList<Integer>>();
    //Type mismatch: cannot convert from ArrayList<ArrayList<Integer>> to List<List<Integer>>

    while (values.size() > numValuesInClause) {
        List<Integer> sublist = values.subList(0,numValuesInClause);
        List<Integer> values2 = values.subList(numValuesInClause, values.size());   
        values = values2; 

        newList.add( sublist);
    }
    return newList;
}

I want to pass in a list of integers, and split it out in to multiple lists of less that size numValuesInClause.

I'm having difficulty with this code, with various conversions/casting between ArrayList<Integer> and List<Integer>

For example List.subList(x,y) returns a List<E>

What's the best way to work here?

The current code shown here is what makes the most sense to me, but has the compilation error shown.

like image 516
dwjohnston Avatar asked Nov 22 '25 04:11

dwjohnston


1 Answers

Use:

List<List<Integer>> newList = new ArrayList<List<Integer>>();

instead of:

List<List<Integer>> newList = new ArrayList<ArrayList<Integer>>();

The reason for this, is that you are instantiating a concrete ArrayList of a generic element List<Integer>>

like image 161
morgano Avatar answered Nov 24 '25 21:11

morgano