转换一个ArrayList的子列表到一个ArrayList [英] Converting a subList of an ArrayList to an ArrayList

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

问题描述

使用im一个ArrayList和IM尝试它的一部分复制到另一个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和键或this.keys是老的ArrayList。
我用铸造因为Eclipse告诉我这样做,但它抛出一个 ClassCastException异常

java.util.ArrayList中$ SUBLIST不能转换到的java.util.ArrayList

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

任何意见?

推荐答案

子列表返回的视图的现有名单上。这不是一个的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 的类型更改为只是列表&LT;整数GT; 而不是的ArrayList&LT;整数GT; ,这样就不需要使复印件:

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 (例如添加值或变更现有的元素)?你要变异?你想一个列表的突变影响其他?

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的子列表到一个ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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