Understanding Java List Usage with Examples

java list

A List in Java is an interface in the java.util package which keeps all items in a specific order and allows duplicates. A List allows you to work with items in an indexed way, allowing developers to add, access, or remove items using an index efficiently. The most common implementations of Lists are the ArrayList, LinkedList and Vector.

Lists are a fundamental feature of Java development as they allow you to hold and manage groups of items. They are also more convenient than an array because they allow you to change the size (dynamically) of the List at runtime. Developers typically use the List when working with items that change over time (user input, database records, things streaming in real time, etc).

In this article, we will explain how Java Lists function, compare and contrast the various implementations of Lists, and provide examples of the typical operations developers do when using Lists. This will include describing iteration challenges and techniques, how to convert from arrays to Lists and back again, and best practices based on the Java Collections Framework (JCF).

What is a Java List?

The Java List interface provides a contract for ordered collections that contain duplicates. The List interface extends Collection and introduces methods to control what can be placed into the collection and where. The collections that implement the List interface extend the collection when they need to include the index to locate the specific item using a zero-based index.

The List interface is located in the hierarchy of Java Collections below Collection and above the ArrayList, LinkedList, and Vector implementations of List. The classes invoke the method structure from the List interface, so these classes have expected behavior.

The major characteristics of Java List include a defined ordered iteration for the collection, element duplication and obtaining elements via index and insertion of elements in an ordered collection that duplicates allows the item to be retrieved using index.  The List data structure is helpful when maintaining order and duplication is required.

List Interface: Core Concepts

The List interface provides a well defined way of storing and managing ordered collections in Java. It provides access to elements by index and allows duplicates. If developers need to deal with ordered elements and/or random access, they will use the List.

To use one of the List implementations, you can first declare it with the List interface and then instantiate it with one of the implementations (like ArrayList). This way you have flexibility with programming and can change the implementation without having to change any structure in the code:

import java.util.*;

public class BasicListExample {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");

        System.out.println(names);
    }
}
output code execution

The example shown here shows the basic java List syntax. The List holds a collection of String elements, maintains the order of insertion, and allows duplicates. The List interface is defined to behave in a consistent manner regardless of the implementation that is used. So the List to be a favorite for many developers.

Java List Implementations

There are multiple List implementations in Java, each with some different internal structure and performance.  The most common List implementations are: ArrayList, LinkedList, and Vector. Each has its own characteristics and the one you should use will depend on the operations you expect to perform.

ArrayList

ArrayList uses a dynamic array to store elements. It provides constant-time performance for access operations using an index. When elements are added beyond its current capacity, it resizes automatically, which may slightly affect performance during that operation.

Use ArrayList when you need fast read operations and minimal insertions or deletions, especially in the middle of the list:

import java.util.*;
public class ArrayListExample {
    public static void main(String[] args) {
        List<String> cities = new ArrayList<>();
        cities.add("New York");
        cities.add("London");
        cities.add("Tokyo");

        System.out.println(cities.get(1)); // Output: London
    }
}
array list output

The ArrayList implementation uses a dynamic array to store its elements. It provides constant time performance for access operations by index.  The ArrayList will resize automatically once you attempt to add elements that are greater than the size of its existing capacity.  But that resize operation can take some time, therefore, you could be affected in performance that one time. Have a look at the demo below:

LinkedList

A linked list is a node-based data structure where each item is linked to subsequent items. It is efficient based on the timeframe for inserting and deleting items, particularly when inserting at the beginning or middle of the list.

A linked list should be considered when you are working on applications where new items are regularly added and not necessarily removed, as it doesn’t allow for fast index based access:

import java.util.*;

public class LinkedListExample {
    public static void main(String[] args) {
        List<String> tasks = new LinkedList<>();
        tasks.add("Task 1");
        tasks.add("Task 2");
        tasks.remove(0);

        System.out.println(tasks.get(0)); // Output: Task 2
    }
java link examples

This Java linked list example shows how to use the add and remove capability. A linked list is helpful when dealing with large datasets that also include constant deletions or insertions of new items. For better understanding learn about How to Clean up Your wp_options Table and Autoloaded Data.

Vector

A Vector is a legacy implementation of the List interface. A Vector is similar to List and ArrayList, but it uses synchronization, making it thread-safe. This means that only one thread can access a Vector at any given time, which is potentially slower than an ArrayList in a single-threaded environment.

So typically, unless synchronization is needed, most developers don’t use the vector class and resort to using an ArrayList with external synchronization if needed:

import java.util.*;

public class VectorExample {
    public static void main(String[] args) {
        List<String> logs = new Vector<>();
        logs.add("Log A");
        logs.add("Log B");

        System.out.println(logs.size()); // Output: 2
    }
}
code execution

This Vector example runs through a normal example of use and comparison. The comparison of Vector vs ArrayList as stated, includes that ArrayLists are a faster alternative without concurrency.

Common Operations on a Java List

Java Lists and interface implementations provide support for List operations (adding, removing, accessing, updating), checking the size and also checking whether the list is empty. All List implementations support the same operations regardless of type.

import java.util.*;

public class CommonOperationsExample {
    public static void main(String[] args) {
        List<String> items = new ArrayList<>();
        items.add("Pen");
        items.add(1, "Notebook");

        items.remove("Pen");
        if (!items.isEmpty()) {
            items.remove(0);
        }

        items.add("Marker");

        if (!items.isEmpty()) {
            String firstItem = items.get(0);
            System.out.println("First item: " + firstItem);
        }

        int count = items.size();
        boolean empty = items.isEmpty();

        System.out.println("Count: " + count);
        System.out.println("Is empty: " + empty);
    }
}
first item code

These Java List methods provide basic functionality for data handling, allowing developers to build efficient and reliable list-based operations. To know more about, read How to Fix render-blocking JavaScript CSS in WordPress.

List vs Array in Java

Both arrays and Lists are available in Java to hold multiple elements but they are used for different reasons and have different properties. Knowing the differences will assist in selecting the right structure based on what you need it to do.

Key Differences

  • Size: Arrays have a fixed size. Lists can grow or shrink dynamically.
  • Data Type: Arrays can hold both primitives and objects. Lists can only store objects.
  • Methods: Arrays have limited built-in methods. Lists provide a wide range of operations, such as add, remove, and contains.
  • Type Safety: Arrays support compile-time type checking. Lists require type specification through generics.

When to Use a List Over an Array

When it is possible that you will not have a fixed number of elements or when you may want to insert or delete items often:

import java.util.*;

public class ListVsArrayExample {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");

        int[] numbers = {10, 20, 30};
        System.out.println(numbers[1]); // Output: 20
    }
}
output code successful

In this instance, you have Examples demonstrating how Lists will resize automatically which makes them the proper substitute for a dynamic array in Java.

When to Use an Array Over a List

Use an array when working with a fixed number of elements or when you need to store primitive types like int or char.

To conclude, Lists allow you to be flexible and have more functionality, while arrays are useful for a static lightweight solution for holding data.

Conversion Between Array and List

Prevalent in Java is seamless conversion between arrays and Lists. It may be important if your task requires switching between a data structure that is fixed size, and one that allows for dynamic resizing. Both the Arrays and the ArrayList class will have built-in methods that can convert arrays to Lists and vice-versa, and those methods will be developed through the remainder of this resource in justifiable time.

Convert List to Array

To convert a List to an array, use the toArray() method. This is helpful when an API requires an array input:

import java.util.*;

public class ListToArrayExample {
    public static void main(String[] args) {
        List<String> colors = new ArrayList<>();
        colors.add("Red");
        colors.add("Blue");

        String[] colorArray = colors.toArray(new String[0]);
        System.out.println(colorArray[1]); // Output: Blue
    }
}
convert list to array

Convert Array to List

To convert an array to a List, use Arrays.asList(). This creates a fixed-size List backed by the original array.

import java.util.*;

public class ArrayToListExample {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Banana", "Orange"};
        List<String> fruitList = Arrays.asList(fruits);

        System.out.println(fruitList.get(0)); // Output: Apple
    }
}
convert array to list

You may find these methods will provide a simple convert between List formats and array formats, giving you some flexibility; while also working with the appropriate structure based on your need.

Conclusion

Java Lists are important for using ordered collections that allow duplicates and index-based operations. The List interface allows for multiple implementations such as ArrayList, LinkedList, and Vector. Each can be used for different situations. Lists allow for flexibility and dynamic sizing and have many built-in methods simplifying managing the data.

In this article, we reviewed the syntax and common operations and using of List example in Java.  We put List side by side an arrays and also we mentioned how convert them to one another. Learning when to use each type of List will help in performance and clean code. Utilizing these concepts will allow developers to build efficient Java applications that maintain data collections.

If you’re developing or running resource-intensive Java programs, consider Ultahost’s managed VPS hosting plan. Our hosting offers the flexibility and control of a dedicated server which means you can install the specific Java version your application requires and configure your server settings to optimize performance for your Java workloads.

FAQ

What is the main difference between a Java List and an array?
Which List implementation should I use for fast access?
When should I prefer LinkedList over ArrayList?
Can a Java List store primitive data types?
Is Vector still used in modern Java development?
How do I convert a List to an array?
Can I create a List from an existing array?

Related Post

java string integer

How to Convert String to Integer in Java

Java usually thinks of user input or data as a string, ...

Leave a Comment