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 a LinkedList and add elements to it:
import java.util.LinkedList; public class Main { public static void main(String[] args) { LinkedList<String> list = new LinkedList<>(); list.add("apple"); list.add("banana"); list.add("cherry"); System.out.println(list); // prints [apple, banana, cherry] } }Sourec:www.lautturi.com
This creates a new LinkedList
object and adds three strings to it using the add
method.
You can also use the addFirst
and addLast
methods to add elements to the beginning or end of the list, respectively. For example:
import java.util.LinkedList; public class Main { public static void main(String[] args) { LinkedList<String> list = new LinkedList<>(); list.addFirst("apple"); list.addLast("banana"); list.addLast("cherry"); System.out.println(list); // prints [apple, banana, cherry] } }
To access an element of the list, you can use the get
method. For example:
import java.util.LinkedList; public class Main { public static void main(String[] args) { LinkedList<String> list = new LinkedList<>(); list.add("apple"); list.add("banana"); list.add("cherry"); String secondElement = list.get(1); // gets the second element (banana) System.out.println(secondElement); // prints banana } }