Home >Java >javaTutorial >Use the size() method of the LinkedList class to get the number of elements in the linked list
Use the size() method of the LinkedList class to obtain the number of elements in the linked list
LinkedList is a doubly linked list implementation class in the Java collection framework. It provides a series of convenient methods for operating linked lists. Among them, the size() method can be used to obtain the number of elements stored in the LinkedList object.
Let’s look at a sample code below to demonstrate how to use the size() method of LinkedList to obtain the number of elements in the linked list:
import java.util.LinkedList; public class LinkedListExample { public static void main(String[] args) { // 创建一个LinkedList对象 LinkedList<String> linkedList = new LinkedList<>(); // 向链表中添加元素 linkedList.add("Java"); linkedList.add("Python"); linkedList.add("C++"); // 使用size()方法获取链表中的元素数量 int size = linkedList.size(); // 输出元素数量 System.out.println("链表中的元素数量为:" + size); } }
Running the above code, we can get the following output:
链表中的元素数量为:3
In the above example, we first created an empty LinkedList object. Then, three elements were added to the linked list using the add() method: "Java", "Python", and "C". Finally, by calling the size() method, we get the number of elements in the linked list and output the result to the console.
It should be noted that the time complexity of the size() method is O(1), that is, it does not increase as the number of elements in the linked list increases. This is because the underlying implementation of LinkedList uses a two-way linked list, which records the length of the linked list by maintaining a variable. Therefore, no matter how many elements there are in the linked list, the size() method can return the result in constant time.
To sum up, using the size() method of LinkedList can easily obtain the number of elements in the linked list, regardless of the number of elements in the linked list. This is very useful when we need to know the size of the linked list when working with it. Hope this article can help you better understand the method of getting the number of elements using LinkedList.
The above is the detailed content of Use the size() method of the LinkedList class to get the number of elements in the linked list. For more information, please follow other related articles on the PHP Chinese website!