Size of LinkedList

Its very important to know the size of LinkedList as it is required in most of the times while coding

We have size() method in LinkedList class which helps us to determine the size of LinkedList

Size is the number of elements in that LinkedList

public int size()


Example :

  1. import java.util.*;
  2.  
  3. public class LinkedListSize {
  4.       public static void main(String[] args) {
  5.       LinkedList<Integer> list = new LinkedList<Integer>();
  6.       list.add(14);
  7.       list.add(7);
  8.       list.add(21);
  9.       list.add(28);
  10.       list.add(35);
  11.       list.add(42);  
  12.       System.out.println("Initial Size of LinkedList: "+list.size());
  13.       list.remove(1);
  14.       list.remove(2);
  15.       System.out.println("Size after removing 2 elements: "+list.size());
  16.       System.out.println("Final LinkedList after removal of 2 elements: ");
  17.       for(int ele: list){
  18.            System.out.println(ele);
  19.         }
  20.     }
  21. }
import java.util.*;

public class LinkedListSize {
      public static void main(String[] args) {
      LinkedList<Integer> list = new LinkedList<Integer>();
      list.add(14);
      list.add(7);
      list.add(21);
      list.add(28);
      list.add(35);
      list.add(42);	 
      System.out.println("Initial Size of LinkedList: "+list.size());
      list.remove(1);
      list.remove(2);
      System.out.println("Size after removing 2 elements: "+list.size());
      System.out.println("Final LinkedList after removal of 2 elements: ");
      for(int ele: list){
           System.out.println(ele);
        }
	}
}


Here Size just tells how many elements are present in the LinkedList

Don’t get confuse size with capacity in the LinkedList, we will talk about capacity separately

Just remember Size() returns number of elements present in LinkedList

Remember size() is a method , not a variable in the LinkedList class.

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on