Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); 
like image 497
J L Avatar asked Apr 27 '12 02:04

J L


People also ask

How do you initialize a linked list by value?

First, we create a LinkedList of type Integer and provide an array of Integers converted to list using the asList method as initial values for the LinkedList. Next, we create an empty LinkedList of type String and then using the add method, we add values to the LinkedList.

How do you assign a value to a linked list in Java?

LinkedList set() Method in Java util. LinkedList. set() method is used to replace any particular element in the linked list created using the LinkedList class with another element. This can be done by specifying the position of the element to be replaced and the new element in the parameter of the set() method.


1 Answers

You can do that this way:

List<Double> temp1 = new LinkedList<Double>(Arrays.asList(1.0, 2.0)); 
like image 200
Eugene Retunsky Avatar answered Sep 20 '22 19:09

Eugene Retunsky