Stack Overflow archive
0 score

Linked List Constructor with initial value

score
0
question views
4.2K
license
CC BY-SA 3.0

Does your class extend LinkedList? If so, here is what I would do:

java
public class MyLinkedList extends LinkedList<String> {

    ...

    public MyLinkedList(String... array) {
        super();
        if (array != null && array.length > 0) {
            for (String s : array) {
                add(s);
            }
        }
    }

    ...

}

It isn't a great idea to extend LinkedList. If you want an easy way to create a new LinkedList with elements use the following method:

java
public static <E> LinkedList<E> newLinkedList(
        @SuppressWarnings("unchecked") final E... elements) {
    final LinkedList<E> list = new LinkedList<E>();
    Collections.addAll(list, elements);
    return list;
}

....

LinkedList<String> yourList = newLinkedList("foo", "bar", "baz");

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.