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

Java Collections · Basic · question 6 of 100

How do you remove an element from a List in Java?

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

In Java, you can remove an element from a List using the "remove" method. The "remove" method removes the specified element from the List, if it is present. If the List does not contain the element, the "remove" method has no effect.

There are two versions of the "remove" method: one that takes an index as an argument, and one that takes an object as an argument. The version that takes an index as an argument removes the element at the specified index, while the version that takes an object as an argument removes the first occurrence of the specified element in the List.

Here’s an example of how to remove an element from a List in Java:

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

public class Example {
    public static void main(String[] args) {
        // create a list
        List<String> myList = new ArrayList<>();
        myList.add("apple");
        myList.add("banana");
        myList.add("orange");
        
        // remove an element at index 1
        myList.remove(1);
        
        // remove the first occurrence of "orange"
        myList.remove("orange");
        
        // print out the contents of the list
        System.out.println("List: " + myList);
    }
}

In this example, we create a List called "myList" using the ArrayList class, and add some strings to it using the "add" method. We then remove an element at index 1 using the "remove" method with an index of 1, and remove the first occurrence of the string "orange" using the "remove" method with an object argument of "orange". Finally, we print out the contents of the List using the "println" method.

The output of this program would be:

List: [apple]

As you can see, the List now contains only the element "apple", as the element at index 1 ("banana") and the first occurrence of "orange" have been removed using the "remove" method.

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