Search code examples
javaarraylistjava-8classcastexception

What is the view of List.sublist(n,m)?


I'm trying to cut an ArrayList<String> in 2 halves.

ArrayList<String> in = new ArrayList<>(), out1, out2;
out1 = (ArrayList<String>) in.subList(0,2); //will cause an ClassCastException: List cannot be casted to ArrayList
out2 = (ArrayList<String>) in.subList(2,5); // either here

Why? what is the view representing, which subList returns?


Solution

  • ArrayList's subList method returns an instance of an inner class of ArrayList called SubList (private class SubList extends AbstractList<E> implements RandomAccess), not an ArrayList. You can store it in a List variable, but you can't cast it to an ArrayList.

    If you want your sub list to be an independant ArrayList, you can create a new ArrayList :

    out1 = new ArrayList<String> (in.subList(0,2)); 
    out2 = new ArrayList<String> (in.subList(2,5));