简体   繁体   English

将ArrayList的subList转换为ArrayList

[英]Converting a subList of an ArrayList to an ArrayList

Im using an ArrayList and im trying to copy a part of it to another ArrayList therefore im using: 我使用ArrayList并尝试将其一部分复制到另一个ArrayList,因此我使用:

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. 其中“sibling.keys”是新的ArrayList,“keys或this.keys”是旧的ArrayList。 I used the casting because eclipse told me to do that but then it throws a ClassCastException : 我使用了转换,因为eclipse告诉我这样做但是它抛出了ClassCastException

java.util.ArrayList$SubList cannot be cast to java.util.ArrayList java.util.ArrayList $ SubList无法强制转换为java.util.ArrayList

Any advice? 有什么建议?

subList returns a view on an existing list. subList返回现有列表上的视图 It's not an ArrayList . 它不是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的类型更改为List<Integer>而不是ArrayList<Integer> ,这样您就不需要进行复制:

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

It's important that you understand the difference though - are you going to mutate sibling.keys (eg adding values to it or changing existing elements)? 重要的是你要理解其中的区别 - 你是否要改变sibling.keys (例如sibling.keys添加值或更改现有元素)? Are you going to mutate keys ? 你要改变keys吗? Do you want mutation of one list to affect the other? 你想要一个列表的变异影响另一个吗?

You get the class cast exception because you are expecting an ArraList while the ArrayList.subList()does not return ArrayList. 你得到类强制转换异常,因为你期望一个ArraList,而ArrayList.subList()不返回ArrayList。 Change your sibling.keys from ArrayList to List , and should work fine. 将您的sibling.keys从ArrayList更改为List ,并且应该可以正常工作。 This will avoid ClassCastException as well as you will not need to and any cast. 这将避免ClassCastException以及您不需要和任何强制转换。

Array.subList doesn't return an ArrayList , but a List . Array.subList不返回ArrayList ,而是返回List

So the following line works : 所以以下行有效:

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

Note that the cast is optional. 请注意,演员阵容是可选的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM