-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy pathCreateLinkedListExample.java
38 lines (30 loc) · 1.39 KB
/
CreateLinkedListExample.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class CreateLinkedListExample {
public static void main(String[] args) {
// Creating a LinkedList
LinkedList<String> friends = new LinkedList<>();
// Adding new elements to the end of the LinkedList using add() method.
friends.add("Rajeev");
friends.add("John");
friends.add("David");
friends.add("Chris");
System.out.println("Initial LinkedList : " + friends);
// Adding an element at the specified position in the LinkedList
friends.add(3, "Lisa");
System.out.println("After add(3, \"Lisa\") : " + friends);
// Adding an element at the beginning of the LinkedList
friends.addFirst("Steve");
System.out.println("After addFirst(\"Steve\") : " + friends);
// Adding an element at the end of the LinkedList (This method is equivalent to the add() method)
friends.addLast("Jennifer");
System.out.println("After addLast(\"Jennifer\") : " + friends);
// Adding all the elements from an existing collection to the end of the LinkedList
List<String> familyFriends = new ArrayList<>();
familyFriends.add("Jesse");
familyFriends.add("Walt");
friends.addAll(familyFriends);
System.out.println("After addAll(familyFriends) : " + friends);
}
}