将 ArrayList 的 subList 转换为 ArrayList [英] Converting a subList of an ArrayList to an ArrayList

查看:44
本文介绍了将 ArrayList 的 subList 转换为 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个 ArrayList 并且我试图将它的一部分复制到另一个 ArrayList 因此我使用:

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);

其中sibling.keys"是新的ArrayList,而keys or this.keys"是旧的ArrayList.我使用了强制转换,因为 eclipse 告诉我这样做,但它抛出一个 ClassCastException:

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 不能转换为 java.util.ArrayList

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

有什么建议吗?

推荐答案

subList 返回现有列表上的 view.它不是 ArrayList.您可以创建它的副本:

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));

或者,如果您对视图行为感到满意,请尝试将 sibling.keys 的类型更改为 List 而不是 ArrayList<;Integer>,这样你就不需要复制了:

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);

但重要的是您了解差异 - 您是否要改变 sibling.keys(例如,向其添加值或更改现有元素)?你要改变 keys 吗?你想让一个列表的变异影响另一个吗?

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?

这篇关于将 ArrayList 的 subList 转换为 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆