📜  Java LinkedList(1)

📅  最后修改于: 2023-12-03 15:01:31.256000             🧑  作者: Mango

Java LinkedList

The Java LinkedList is a data structure that represents a collection of elements in a sequential manner. It is a class that is implemented in the java.util package and is a commonly used alternative to an array when there is a need for faster insertions and deletions of elements.

Creating a LinkedList

To create a LinkedList in Java, we first need to import the LinkedList class from the java.util package. We can then create an instance of LinkedList as shown below:

import java.util.LinkedList;

LinkedList<String> myList = new LinkedList<String>();

In the above code, we create an empty LinkedList of type String which means that it will hold elements of String data type. We can also create a LinkedList of any other data type like Integer, Float, Double, etc.

Adding Elements to a LinkedList

Adding elements to a LinkedList is a straightforward process. We can add elements to a LinkedList using the add() method. Below is an example of how to add elements to a LinkedList:

myList.add("John");
myList.add("Alice");
myList.add("Bob");

In the above code, we add three elements to the LinkedList named myList. The add() method adds elements to the end of the LinkedList.

Removing Elements from a LinkedList

We can remove elements from a LinkedList using the remove() method. The remove() method removes the first occurrence of the specified element from the LinkedList. Below is an example of how to remove an element from a LinkedList:

myList.remove("Alice");

In the above code, we remove the element "Alice" from the LinkedList named myList.

Accessing Elements in a LinkedList

We can access elements in a LinkedList using the get() and indexOf() methods. The get() method returns the element at the specified index, and the indexOf() method returns the index of the first occurrence of the specified element. Below is an example of how to access elements in a LinkedList:

String element = myList.get(0);
int index = myList.indexOf("John");

In the above code, we access the first element of the LinkedList named myList and also the index of the first occurrence of the element "John".

Conclusion

LinkedList is a powerful data structure that provides efficient insertion and deletion operations. It is widely used in various applications and is a must-know topic for any Java programmer.