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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With