Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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?

like image 712
yoavgray Avatar asked May 20 '13 07:05

yoavgray


People also ask

What is the way to get subList from an ArrayList in Java?

The subList() method of java. util. ArrayList class is used to return a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.)

Does subList create a new list?

subList is a method in the List interface that lets you create a new list from a portion of an existing list. However, this newly created list is only a view with a reference to the original list.

Is subList inclusive?

subList() Method Parameters. fromIndex – start index in existing arraylist. It is inclusive.


1 Answers

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?

like image 97
Jon Skeet Avatar answered Oct 27 '22 18:10

Jon Skeet