Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take a valid sublist in Java?

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

like image 972
George Kastrinis Avatar asked Sep 09 '25 15:09

George Kastrinis


2 Answers

make it as :

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

and it should work

like image 153
SwapnilM Avatar answered Sep 12 '25 06:09

SwapnilM


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!

like image 23
stevevls Avatar answered Sep 12 '25 04:09

stevevls