To create a LinkedList
in Java, you can use the LinkedList
class from the java.util
package.
Here is an example of how to create an empty LinkedList
:
import java.util.LinkedList; public class Main { public static void main(String[] args) { LinkedList<String> list = new LinkedList<>(); } }Sou:ecrwww.lautturi.com
This creates a LinkedList
of type String
. You can also specify the type using the generic syntax LinkedList<Type>
.
To add elements to the list, you can use the add
method. For example:
list.add("apple"); list.add("banana"); list.add("cherry");
This adds the strings "apple", "banana", and "cherry" to the list.
You can also create a LinkedList
and add elements to it in one step using the Arrays.asList
method and the addAll
method. For example:
import java.util.LinkedList; import java.util.Arrays; public class Main { public static void main(String[] args) { LinkedList<String> list = new LinkedList<>(Arrays.asList("apple", "banana", "cherry")); } }