make ArrayList Read only

JavaCollectionsJakarta EeArraylist

Java Problem Overview


In Java, how can you make an ArrayList read-only (so that no one can add elements, edit, or delete elements) after initialization?

Java Solutions


Solution 1 - Java

Pass the ArrayList into Collections.unmodifiableList(). It returns an unmodifiable view of the specified list. Only use this returned List, and never the original ArrayList.

Solution 2 - Java

Pass the list object to Collections.unmodifiableList(). See the example below.

import java.util.*;

public class CollDemo
{
    public static void main(String[] argv) throws Exception
    {
        List stuff = Arrays.asList(new String[] { "a", "b" });
        List list = new ArrayList(stuff);
        list = Collections.unmodifiableList(list);
        Set set = new HashSet(stuff);
        set = Collections.unmodifiableSet(set);
        Map map = new HashMap();
        map = Collections.unmodifiableMap(map);
        System.out.println("Collection is read-only now.");
    }
}

Solution 3 - Java

Are you sure you want to use an ArrayList in this case?

Maybe it would be better to first populate an ArrayList with all of your information, and then convert the ArrayList into a final array when the Java program initializes.

Solution 4 - Java

Pass the collection object to its equivalent unmodifiable function of Collections class. The following code shows use of unmodifiableList

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class Temp {

    public static void main(String[] args) {

	    List<Integer> objList = new ArrayList<Integer>();
	    objList.add(4);
	    objList.add(5);
	    objList.add(6);
	    objList.add(7);

	    objList = Collections.unmodifiableList(objList);
	    System.out.println("List contents " + objList);

	    try {
		    objList.add(9);
	    } catch(UnsupportedOperationException e) {
		    e.printStackTrace();
		    System.out.println("Exception occured");
	    }
	    System.out.println("List contents " + objList);
    }

}

same way you can create other collections unmodifiable as well

Solution 5 - Java

You can use this as a convenient way to initialize your ordered immutable List.

List<Integer> unmodifiableList = List.of(1,2,3,4,5);

> Unmodifiable Lists Source > > The List.of and List.copyOf static factory methods provide a > convenient way to create unmodifiable lists. The List instances > created by these methods have the following characteristics: > > - They are unmodifiable. Elements cannot be added, removed, or replaced. Calling any mutator method on the List will always cause > UnsupportedOperationException to be thrown. However, if the contained > elements are themselves mutable, this may cause the List's contents to > appear to change. > - They disallow null elements. Attempts to create them with null elements result in NullPointerException. > - They are serializable if all elements are serializable. > - The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array. > - The lists and their subList views implement the RandomAccess interface. > - They are value-based. Programmers should treat instances that are equal as interchangeable and should not use them for synchronization, > or unpredictable behavior may occur. For example, in a future release, > synchronization may fail. Callers should make no assumptions about the > identity of the returned instances. Factories are free to create new > instances or reuse existing ones. > - They are serialized as specified on the Serialized Form page.

Note: Though other answers also work and answer the question, I feel like this tidbit adds value to the overall conversation.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongmhkView Question on Stackoverflow
Solution 1 - JavaMark PopeView Answer on Stackoverflow
Solution 2 - JavaArunkumar PapenaView Answer on Stackoverflow
Solution 3 - JavaJama22View Answer on Stackoverflow
Solution 4 - JavaAmar MagarView Answer on Stackoverflow
Solution 5 - JavaAtspulgsView Answer on Stackoverflow