Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 794
Joel Avatar asked Oct 19 '22 07:10

Joel


1 Answers

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));
like image 136
Eran Avatar answered Oct 28 '22 20:10

Eran