To add elements to a LinkedList
in Java, you can use the add
method of the LinkedList
class.
The add
method adds a new element to the end of the LinkedList
, and it takes a single argument that specifies the value of the element to be added.
Here is an example of how you can add elements to a LinkedList
in Java:
import java.util.LinkedList; public class Main { public static void main(String[] args) { // Create a LinkedList LinkedList<String> list = new LinkedList<>(); // Add some elements to the LinkedList list.add("Apple"); list.add("Banana"); list.add("Orange"); // Print the LinkedList System.out.println(list); // Output: [Apple, Banana, Orange] } }
In this example, the list
variable is a LinkedList
that stores strings.
The add
method is used to add three elements to the LinkedList
: "Apple", "Banana", and "Orange".
Then, the list
variable is printed, and it contains the three elements that were added to the LinkedList
.
It is important to note that the add
method adds the element to the end of the LinkedList
, and it always returns true
.
Therefore, you can use the add
method to append elements to the LinkedList
, but you cannot use it to insert elements at a specific position in the LinkedList
.
To insert an element at a specific position in a LinkedList
, you can use the add
method of the List
interface, which takes two arguments: the index at which the element is to be inserted, and the element to be inserted.
Here is an example of how you can insert an element at a specific position in a LinkedList
:
list.add(1, "Peach");
In this example, the element "Peach" is inserted at the index 1, which is the second position in the LinkedList
.
After this operation, the LinkedList
contains the following elements: "Apple", "Peach", "Banana".