Java LinkedList size() Method
size()The method is in JavaLinkedLista commonly used method provided by the class, which belongs tojava.utilthe package. The main purpose of this method is to return the number of elements in the current linked list.
Method Syntax:
Return Value:
- Returns
inta value of type, representing the number of elements in the linked list - If the linked list is empty, it returns 0
Method Characteristics
Time Complexity
size()The time complexity of the method is O(1), which means that no matter how many elements the linked list contains, the time to obtain the size is constant.
This is becauseLinkedListthe class internally maintains asizevariable, which is automatically updated when elements are added or removed. Callingsize()the method simply returns the value of this variable.
Difference from Array length
Beginners sometimes confusesize()the method with the array'slengthproperty:
- The array's
lengthis a property that represents the capacity of the array LinkedListofsize()is a method that returns the number of elements actually stored
Thread Safety
size()The method itself is not thread-safe. If used in a multi-threaded environment, additional synchronization measures are required.
Usage Examples
Basic Usage
Example
public class LinkedListSizeDemo {
public static void main(String[] args) {
// Create a LinkedList
LinkedList<String> fruits = new LinkedList<>();
// Add elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// Use the size() method to get the number of elements
int size = fruits.size();
System.out.println("Number of elements in LinkedList: " + size); // Output: 3
}
}
Empty Linked List Case
Example
public class EmptyLinkedListDemo {
public static void main(String[] args) {
LinkedList<Integer> numbers = new LinkedList<>();
System.out.println("Size of empty linked list: " + numbers.size()); // Output: 0
}
}
Dynamic Change Demonstration
Example
public class DynamicSizeDemo {
public static void main(String[] args) {
LinkedList<Character> letters = new LinkedList<>();
System.out.println("Initial size: " + letters.size()); // 0
letters.add('A');
letters.add('B');
System.out.println("After adding two elements: " + letters.size()); // 2
letters.removeFirst();
System.out.println("After removing one element: " + letters.size()); // 1
letters.clear();
System.out.println("After clearing: " + letters.size()); // 0
}
}
Common Questions
Does the size() method throw an exception?
size()The method usually does not throw an exception. Even if the linked list is null (note: not an empty linked list), callingsize()the method will not throw an exception, but will throwNullPointerException。
Example
// The following line will throw a NullPointerException
System.out.println(list.size());
Relationship between size() and isEmpty()
isEmpty()The method is based onsize()the implementation of the method:
Example
return size() == 0;
}
Therefore,list.isEmpty()is equivalent tolist.size() == 0, but the former has better readability.
Practical Application Scenarios
Loop Traversal
Example
colors.add("Red");
colors.add("Green");
colors.add("Blue");
for (int i = 0; i < colors.size(); i++) {
System.out.println(colors.get(i));
}
Capacity Check
Example
// ...add elements...
if (queue.size() > 10) {
System.out.println("Queue is full, cannot add more elements");
}
Comparison with Other Collections
Example
LinkedList<String> list2 = new LinkedList<>();
// ...fill two linked lists...
if (list1.size() == list2.size()) {
System.out.println("The two linked lists have the same size");
}
Performance Considerations
Althoughsize()the method itself has O(1) time complexity, in some cases, frequently callingsize()may have a performance impact:
- Multi-threaded environment: every call to
size()needs to read the in-memorysizevariable - Complex loop conditions: such as
for (int i = 0; i < list.size(); i++), calling it on every loop iterationsize()
For the second case, it can be optimized as:
Example
for (int i = 0; i < size; i++) {
// Loop body
}
Summary
LinkedListofsize()The method is a simple but very important method that provides the ability to quickly obtain the current number of elements in a linked list. Understanding the working principle and characteristics of this method helps to write more efficient and reliable Java code.
Remember:
size()It returns the number of elements, not the capacity- An empty linked list's
size()returns 0 - When using it in a multi-threaded environment, you need to pay attention to synchronization issues
- It can be combined with
isEmpty()method to make the code clearer
Java LinkedList