Converting a subList of an ArrayList to an ArrayLi

2020-05-19 06:37发布

Im using an ArrayList and im trying to copy a part of it to another ArrayList therefore im using:

sibling.keys = (ArrayList<Integer>) keys.subList(mid, this.num);

Where "sibling.keys" is the new ArrayList and "keys or this.keys" is the older ArrayList. I used the casting because eclipse told me to do that but then it throws a ClassCastException:

java.util.ArrayList$SubList cannot be cast to java.util.ArrayList

Any advice?

3条回答
何必那么认真
2楼-- · 2020-05-19 07:05

subList returns a view on an existing list. It's not an ArrayList. You can create a copy of it:

sibling.keys = new ArrayList<Integer>(keys.subList(mid, this.num));

Or if you're happy with the view behaviour, try to change the type of sibling.keys to just be List<Integer> instead of ArrayList<Integer>, so that you don't need to make the copy:

sibling.keys = keys.subList(mid, this.num);

It's important that you understand the difference though - are you going to mutate sibling.keys (e.g. adding values to it or changing existing elements)? Are you going to mutate keys? Do you want mutation of one list to affect the other?

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-05-19 07:27

You get the class cast exception because you are expecting an ArraList while the ArrayList.subList()does not return ArrayList. Change your sibling.keys from ArrayList to List, and should work fine. This will avoid ClassCastException as well as you will not need to and any cast.

查看更多
相关推荐>>
4楼-- · 2020-05-19 07:28

Array.subList doesn't return an ArrayList, but a List.

So the following line works :

List<Integer> keys = (List<Integer>) keys.subList(mid, this.num);

Note that the cast is optional.

查看更多
登录 后发表回答