LinkedList
?A linked list is a collection of linear data elements. Each element (node) contains data and reference parts. The data part has the value and the reference part has the address to the next element.
The elements are not indexed so random access is not possible. Instead, we traverse from the beginning of the list and access the elements.
In Java, the
LinkedList
is aimplementation of the List and Deque interfaces. The doubly-linked list Kind of linked list. Each node contains three fields: two link fields(one for the previous element and another for the next element) and one data field. LinkedList
is class present in thejava.util
package.
size
method of the LinkedList
class?The size
method can be used to get the
public int size()
This method doesn’t take in any arguments. It returns the number of elements present in the list as an integer.
The code below demonstrates how to use the size
method.
import java.util.LinkedList;class LinkedListSize {public static void main( String args[] ) {LinkedList<String> list = new LinkedList<>();list.add("1");list.add("2");list.add("3");System.out.println("The list is " + list);System.out.println("The size of list is : " + list.size());}}
In the code above:
LinkedList
class.import java.util.LinkedList;
LinkedList
object with the name list
.LinkedList<String> list = new LinkedList<>();
add
method of the list object to add three elements ("1","2","3"
) to the list.list.add("1");
list.add("2");
list.add("3");
size
method of the list object to get the size of the list. In our case, 3
will be returned because the list
object has 3
elements.list.size(); // 3