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
make it as :
List sublist = new ArrayList();
sublist = new ArrayList<String>(alist.subList(2, 4));
and it should work
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
(not ArrayList
). 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!
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