The LinkedList.size()
method in Java is used to return the number of elements in the LinkedList
. This guide will cover the method’s usage, explain how it works, and provide examples to demonstrate its functionality.
Table of Contents
- Introduction
size
Method Syntax- Examples
- Getting the Size of a LinkedList
- Using Size in Conditional Statements
- Conclusion
Introduction
The LinkedList.size()
method is a member of the LinkedList
class in Java. It provides a way to determine the number of elements currently stored in the LinkedList
. This method is particularly useful for iterating over the list, performing validations, or simply understanding the list’s current state.
size Method Syntax
The syntax for the size
method is as follows:
public int size()
- Returns: The number of elements in the
LinkedList
.
Examples
Getting the Size of a LinkedList
The size
method can be used to get the number of elements in a LinkedList
.
Example
import java.util.LinkedList;
public class SizeExample {
public static void main(String[] args) {
// Creating a LinkedList of Strings
LinkedList<String> list = new LinkedList<>();
// Adding elements to the LinkedList
list.add("Apple");
list.add("Banana");
list.add("Orange");
// Getting the size of the LinkedList
int size = list.size();
// Printing the size of the LinkedList
System.out.println("Size of LinkedList: " + size);
}
}
Output:
Size of LinkedList: 3
Using Size in Conditional Statements
You can use the size
method to perform conditional operations based on the number of elements in the LinkedList
.
Example
import java.util.LinkedList;
public class ConditionalSizeExample {
public static void main(String[] args) {
// Creating a LinkedList of Strings
LinkedList<String> list = new LinkedList<>();
// Adding elements to the LinkedList
list.add("Apple");
list.add("Banana");
// Checking if the LinkedList is empty
if (list.size() == 0) {
System.out.println("The LinkedList is empty.");
} else {
System.out.println("The LinkedList is not empty.");
}
// Checking if the LinkedList has more than 2 elements
if (list.size() > 2) {
System.out.println("The LinkedList has more than 2 elements.");
} else {
System.out.println("The LinkedList does not have more than 2 elements.");
}
}
}
Output:
The LinkedList is not empty.
The LinkedList does not have more than 2 elements.
Conclusion
The LinkedList.size()
method in Java provides a way to determine the number of elements in a LinkedList
. By understanding how to use this method, you can efficiently manage collections of objects in your Java applications. Whether you need to iterate over the list, perform validations, or simply understand the current state of the list, the size
method is an essential tool.