Converting a subList of an ArrayList to an ArrayList

后端 未结 2 1165
遇见更好的自我
遇见更好的自我 2021-02-01 13:42

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

sibling.keys = (ArrayList) keys.subList(mid, thi         


        
2条回答
  •  清歌不尽
    2021-02-01 14:23

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

    sibling.keys = new ArrayList(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 instead of ArrayList, 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?

提交回复
热议问题