WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java Collections · Intermediate · question 35 of 100

How do you create an immutable List in Java Collections?

📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

In Java, you can create an immutable List using the Collections.unmodifiableList() method. The unmodifiableList() method returns an unmodifiable view of the specified list. Any attempt to modify the returned list will result in an UnsupportedOperationException.

Here’s an example code that demonstrates how to create an immutable List:

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

public class Example {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("One");
        list.add("Two");
        list.add("Three");
    
        List<String> immutableList = Collections.unmodifiableList(list);
    
        // This will throw an UnsupportedOperationException
        immutableList.add("Four");
    }
}

In this example, we create an ArrayList and add three strings to it. We then create an immutable view of the ArrayList using the Collections.unmodifiableList() method. Finally, we try to add a string to the immutable list, which results in an UnsupportedOperationException.

Note that the elements of the underlying list can still be modified, and the modifications will be reflected in the immutable view. Therefore, you should only use unmodifiableList() to create an immutable view of a list if you’re sure that the elements of the list won’t be modified.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Collections interview — then scores it.
📞 Practice Java Collections — free 15 min
📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

All 100 Java Collections questions · All topics