I have this weird (I think) problem in Java.
I have an ArrayList and I want to take a sublist.
But I get the follow exception.
package javatest;
import java.util.ArrayList;
public class JavaTest {
public static void main(String[] args) {
ArrayList<Integer> alist = new ArrayList<Integer>();
alist.add(10);
alist.add(20);
alist.add(30);
alist.add(40);
alist.add(50);
alist.add(60);
alist.add(70);
alist.add(80);
ArrayList<Integer> sub = (ArrayList<Integer>) alist.subList(2, 4);
for (Integer i : sub)
System.out.println(i);
}
}
run: Exception in thread “main”
java.lang.ClassCastException:
java.util.RandomAccessSubList cannot
be cast to java.util.ArrayList at
javatest.JavaTest.main(JavaTest.java:17)
Java Result: 1
What is the correct way to take a sublist?
Thx
You should work with the interfaces for Collections wherever possible. You’re downcasting the result of sublist, but the API specifies that it returns
List(notArrayList). Here, the implementors are choosing to return a different type to make their lives easier.Furthemore, the API documentation specifies that sublist will return a List mapped onto the original, so beware!