I am am trying to use the LinkedList class to load an array of anything. I was looking at the documentation of addAll method and it seem to me that I could load an array of stuff with very little effort.
addAll(int index, Collection<? extends E> c) Inserts all of the elements in the specified collection into this list, starting at the specified position.
But I am not so sure on how to structure it.
Let’s just say I have an array of Objects and I am trying to load the objects into a link list.
How would I write this?
NOTE: I am trying to load it to a list because I will be deleting and adding at multiple times.
I used below code but I get an error:
int[] a = new int[5];
for(int index = 0; index<5; index++){
a[index] = index;
}
List<Integer> list = new LinkedList<Integer>();
list.addAll(Arrays.asList(a)); //error Here won't take a[]
If you need specifically LinkedList or mutable collection class (you mentioned add/delete operations) then
Arrays.asList(T...)won’t help as it returns a fixed-size list backed by the specified array and hence not mutable andArrays.asList(T...).add(T)call will always fail.If you don’t need an array, use collection classes from start only(like ArrayList or LinkedList). In case if it’s not possible this collection tutorial will give you fair idea about usage and other aspects.
if you wanto to create an ArrayList (or LinkedList) you can use (and it will copy all the elements of an array to List)-
EDIT –
If the array itself is a primitive array (which you shown in example) then above approach will not work either because
Arrays.asList(int[])will actually return single elementList<int[]>and that’s why you’re getting error in your example.If you find yourself working heavily with collection of primitives then I would suggest to look at Trove or may be Guava which provides awesome utilities pertaining to collections and other day to day needs(it has
Ints.asList()method which satisfy your requirement, see doc).