How to find the length (size) of Linked List in Java (Android Studio) – IT Blog
IT Blog
Boris IT Expert

How to find the length (size) of Linked List in Java (Android Studio)

Boris~October 23, 2020 /Linked List

If you want to find the Linked List length on an example of Java, you may follow two ways.
It depends on what way of implementation you used. Firstly, you implement the LinkedList with the help of Java collections. On the other way, you may implement Linked List by creating your model and constructor. For more details about developing and implementing LinkedList in java, you can check on this page.
In Java collections, you can call the .size() method to receive the LinkedList size. Example:

linkedList.size()

Getting the length of Linked List in Java without collections.

If you implemented LinkedList by yourself with the help of model class and constructor, you would have to implement the logic of getting size by yourself. The basic idea here is using some counter that will increment with each iteration. The counter is one of the most common techniques in algorithms. The usage of the counter might be beneficial in any technical interview. Here is an example:

private void countingItemsInLinkedList() {
        ////You need to create linked list first       
        creatingLinkedList();

        //Starts counting value
        int result = 0;
        //Finding the first item from the list
        ListNode current = head;
//Going through the list until last item don't have connection
        while (current != null) {
            //Increasing counter each iteration
            result++;
            current = current.next;
        }
        Log.d("linkedList", "Length = " + result);
    }

A visual explanation of getting the size of Linked List

How to get length of the linked list in java

In this article, you figured out how to find the Linked List length in Java in two ways. With the help of the Java collections and in case of implementation via constructor and model class.

Useful links:

Leave Any Questions Related To This Article Below!