How to take a valid sublist in Java?

George Kastrinis picture George Kastrinis · May 31, 2011 · Viewed 43k times · Source

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

Answer

SwapnilM picture SwapnilM · Dec 15, 2011

make it as :

List sublist = new ArrayList();
sublist = new ArrayList<String>(alist.subList(2, 4));

and it should work