简体   繁体   中英

Using LinkedList Java Class

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 and Arrays.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)-

new ArrayList<Element>(Arrays.asList(array))


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 element List<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 ).

Start by transforming the array into a list, and then add all the elements of this list to your linked list:

List<Foo> list = new LinkedList<Foo>();
list.addAll(Arrays.asList(myArray());

Or just iterate through the array yourself, and add every element:

List<Foo> list = new LinkedList<Foo>();
for (Foo foo : myArray) {
    list.add(foo);
}

which requires just one more line of code, is straightforward, and more efficient.

Note that ArrayList is more efficient than LinkedList in most situations.

您可以使用java.util.Arrays类:

List<MyType> list = Arrays.asList(array);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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