How can I initialize a LinkedList with entries/values in it?
So I know how to have a linked list and use add method to input entries by entries. However, I do not want to add entries by entries. Is there a way to declare a linkedlist with initial values in the list?
For example, if I want to have 1.0 & 2.0 in the list is there something I can do in one line? Something like:
List<Double> temp1 = new LinkedList<Double>(1,2);
Solution 1:
You can do that this way:
List<Double> temp1 = new LinkedList<Double>(Arrays.asList(1.0, 2.0));
Solution 2:
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.
Solution 3:
If you are using JDK9+, you can use List.of(...)
like:
List<Double> myList = new LinkedList<>(List.of(10D, 11D));