How can I initialize a LinkedList with entries/values in it? How can I initialize a LinkedList with entries/values in it? java java

How can I initialize a LinkedList with entries/values in it?


You can do that this way:

List<Double> temp1 = new LinkedList<Double>(Arrays.asList(1.0, 2.0));


LinkedList has the following constructor, which accepts a parameter of type Collection:

public LinkedList(Collection<? extends E> c)

This constructor 'Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.'

Therefore you could use this constructor to declare a LinkedList and initialize it with values at the time of declaration. You can provide an instance of any Collection<Double> type.

If you have only a set of values but not a Collection object, then you can use the java.util.Arrays class which has the static asList() method which will convert the set of values provided to a List and return. See the example below:

 List<Double> list = new LinkedList<Double>(Arrays.asList(1.2,1.3,3.2));

If you need an instance of List<Double> then you have to provide the values with a decimal place, otherwise the you'll get an instance of List<Integer> with the values.


You can also create method like

static <T> LinkedList<T> createLinkedList(T...elements) {    LinkedList<T> newList = new LinkedList<T>();    for (T el : elements) {        newList.add(el);    }    return newList;}

And use it with :

        LinkedList<Integer> a = createLinkedList(1, 2, 3);        for (Integer item : a) {            System.out.println(item);        }