Core Java

Java List methods Tutorial

In this article, we will learn about the Java List methods. List is an ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted.

The user can access elements by their integer index (position in the list), and search for elements in the list. This interface is a member of the Java Collections Framework.

1. Introduction

Unlike sets, lists typically allow duplicate elements. More formally, a Java list, typically allows pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all.

The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

Java List methods - List Class Diagram
Figure 1. Class Diagram

2. List Implementations

Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException.

Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as “optional” in the specification for this interface.

2.1 ArrayList

ArrayList is the most commonly used implementation of List interface. Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be wrapped using the Collections.synchronizedList method.

List arrayList = new ArrayList();

2.2 LinkedList

LinkedList internally uses a doubly linked list to store the elements. Manipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory. LinkedList is better for manipulating data.

List linkedList = new LinkedList();

3. Methods

In this section we will discuss some important methods defined in the List Interface of Java.

3.1 Add

There are several ways to insert an element in the list. The add(E e) method takes the element that needs to be added and appends it at the end of the list. This method will return true if the element is added successfully.

boolean add(E e)

There is another method which takes the index where we want to add the element: void add(int index, E element).

addAll method appends all of the elements in the specified collection to the end of the list, in the order that they are returned by the specified collection’s iterator. There is a similar method to add all elements on the specified index: boolean addAll(int index, Collection c)

3.2 Remove

remove() method removes the first occurrence of the specified element from this list, if it is present. If the element is not present, it is unchanged. It removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).

It throws a ClassCastException if the type of the specified element is incompatible with this list.

There is a similar method boolean removeAll(Collection c) which removes all the elements specified in the param from the list. The retainAll method does the opposite, it retails only the elements in this list that are contained in the specified collection. So it removes from this list all of its elements that are not contained in the specified list.

3.3 Size

The size() method returns the number of elements in the list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

3.4 Contains

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)). It throws a ClassCastException if the type of the specified element is incompatible with the list.

There is a similar method boolean containsAll(Collection c) which returns true if the list contains all of the elements of the specified collection.

3.5 toArray

Returns an array containing all of the elements in this list in proper sequence (from first to last element). The returned array will be safe in that no references to it are maintained by this list. In other words, this method must allocate a new array even if this list is backed by an array. The caller is thus free to modify the returned array.

There is an overloaded method which takes a generic type parameter

 T[] toArray(T[] a)

3.6 Sort

The sort method sorts the list according to the order included by the specified Comparator. All the elements in the list must be mutually comparable using the specified comparator – compare(e1, e2) must not throw a ClassCastException.

If the specified comparator is null then all elements in this list must implement the Comparable interface and the elements’ Comparable natural ordering should be used.

ListExample.java

package com.javacodegeeks;

import java.util.*;

public class ListExample {

    private static List arrayList;

    public static void main(String[] args) {

        // ## List creation
        arrayList = new ArrayList();

        arrayList.add("First");
        arrayList.remove("First");

        arrayList.size();// Size
        arrayList.isEmpty();// Is empty
        arrayList.contains("Does Not Contains"); // Contains

    }

    public List convertStringArrayToList(String[] arr) {
        return Arrays.asList(arr);
    }

    public String[] convertListOfStringsToArray(List list) {
        return list.toArray(new String[0]);
    }

    public static boolean containAll(Collection c) {
        return arrayList.contains(c);
    }

    public static boolean addAll(Collection c) {
        return arrayList.addAll(c);
    }

    public void sort() {
        arrayList.sort(new Comparator() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
    }

}

4. Convert List to Array

In this section we will see how we can convert a list to an array.

The easiest way to convert a list to an array is to use the build-in function toArray().

List list = Stream.of("one", "two", "three").collect(Collectors.toList());
final String[] array = list.toArray(new String[0]);

5. Convert Array to List

In this section we will see how we can convert an array to a list.

The easiest way to convert an array to a List is to use the java.util.Arrays class.

Arrays.asList(arr);

The asList method returns a fixed-size list backed by the specified array. The returned list is serializable and implements RandomAccess.

You can’t use the same method if you have an array of primitive types, like int. To convert an array of primitive types (e.g. int) you can use

Arrays.stream(arrOfIntegers).boxed().collect(Collectors.toList())

Note that this is only available in Java 8 and above.

6. Summary

In this article we discussed about List interface in java and it’s few implementations. We just discussed the two most commonly used implementations. There are others less common as well. Then we discussed some of the important methods in the List interface. To know about more methods you can refer List. In the end we looked how to convert a list to an array and vice-verse.

7. Download the source code

In this article, we learned about the Java List methods through examples.

Download
You can download the full source code of this example here: Java List methods Tutorial

Mohammad Meraj Zia

Senior Java Developer
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button