list in java

Java List Data Structure: Learn Real Use Case Of List

Java has many built in data structures. And one of the data structure in Java is List. Let us learn how it works and why should you use it.

List in Java is an interface, and it cannot be instantiated directly. But java out of the box provides multiple implementations.

I will try to help you understand when you need to use a list.

What is a List datastructure ?

Let me provide you a comprehensive definition of List in Java. I will also mention the details that people might fail to remember about.

Lists are ordered collections, which preserves the sequence of the data in them. Collection itself is an interface which acts as the parent of List.

There are multiple implementations of list in Java: AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack and Vector.

Using Java List: List usage Syntax

Here is a syntax of list, we will use ArrayList because we cannot really create an instance of List itself.

// simple list containing names List names = new ArrrayList<String>();
Code language: JavaScript (javascript)

When to use Java List ?

We have understood what List is. But what is the use-case ? When should you consider using a List.

You should use list almost every time. If you want to use an Array. Chances are you might really want to use the List instead.

An array doesn’t provide any easy way to manage its elements. But with List it is really very easy to add, remove or manipulate the items.

Also it’s worth nothing that under the implementation. It uses array as the base data structure. And the operations for list is quite reasonable.

Time complexity of List

Here is the complexity of list data structure in Java.

.add(element) complexity is only O(1)

.add(index, element) complexity is O(n)

.get(index) is also O(1)

.remove() is always O(n)

.indexOf(element) is also always O(n)

And, .contains() too has time complexity of O(n).

That is it for a short and sweet introduction to list. Nothing much have been explained here. But here is enough information for you to get started.

Also I had previously written another article about ArrayLists in Java. If you want to learn about ArrayList, read here.

Recommended

Push Notifications in Android Using One Signal

Show or Hide Soft Keyboard in Android Application And More

Android View Introduction: What is Android View, Using Views

OnClickListener in Android RecyclerView: Example

Using Bottom Navigation Bar in Android: An Easy Guide

Related Posts