开发者

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


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!


Try this...

List<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);
List<Integer> sub = alist.subList(2, 4);
for (Integer i : sub)
  System.out.println(i);


Try

List<Integer> sub = alist.subList(2, 4);


    public List<E> subList(int fromIndex, int toIndex) {
    return (this instanceof RandomAccess ?
            new RandomAccessSubList<E>(this, fromIndex, toIndex) :
            new SubList<E>(this, fromIndex, toIndex));
    }

like at the ArrayList's impl, it is return List,as @George Kastrinis said use interface wherever possible.


Change the code to:

List<Integer> sub = alist.subList(2, 4);

The sublist() method returns a List, which not necessarily is an ArrayList (here it's actually a RandomAccessSublist, which is why the cast fails).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜