Java LinkedList size() Method

Java LinkedList Java LinkedList


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:

public int size()

Return Value:

  • Returnsinta 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'slengthis 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

import java.util.LinkedList;

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

import java.util.LinkedList;

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

import java.util.LinkedList;

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

LinkedList<String> list = null;
// 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

public boolean isEmpty() {
    return size() == 0;
}

Therefore,list.isEmpty()is equivalent tolist.size() == 0, but the former has better readability.


Practical Application Scenarios

Loop Traversal

Example

LinkedList<String> colors = new LinkedList<>();
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

LinkedList<Integer> queue = new LinkedList<>();
// ...add elements...

if (queue.size() > 10) {
    System.out.println("Queue is full, cannot add more elements");
}

Comparison with Other Collections

Example

LinkedList<String> list1 = new LinkedList<>();
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:

  1. Multi-threaded environment: every call tosize()needs to read the in-memorysizevariable
  2. Complex loop conditions: such asfor (int i = 0; i < list.size(); i++), calling it on every loop iterationsize()

For the second case, it can be optimized as:

Example

int size = list.size();
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'ssize()returns 0
  • When using it in a multi-threaded environment, you need to pay attention to synchronization issues
  • It can be combined withisEmpty()method to make the code clearer

Java LinkedList Java LinkedList

Other Extensions