java arraylist remove

java arraylist remove

To remove an element from an ArrayList in Java, you can use the remove() method of the ArrayList class.

Here is an example of how to remove an element from an ArrayList using the remove() method:

‮‬refer to:lautturi.com
import java.util.ArrayList;

public class ArrayListRemoveExample {

    public static void main(String[] args) {
        ArrayList<String> words = new ArrayList<>();
        words.add("hello");
        words.add("world");
        words.add("goodbye");
        words.add("moon");

        System.out.println("Before: " + words);

        words.remove("world");

        System.out.println("After: " + words);
    }
}

This code creates an ArrayList of strings called words and adds some elements to it. It then uses the remove() method to remove the element "world" from the list. The remove() method takes the element to be removed as an argument and removes the first occurrence of the element from the list.

The remove() method returns a boolean value indicating whether the element was present in the list and was successfully removed. In this example, the remove() method returns true, indicating that the element was present in the list and was removed.

You can also use the remove() method to remove an element at a specific index in the list. To do this, you can pass the index of the element as an argument to the remove() method.

For example, to remove the element at index 1 in the words list, you can use the following code:

words.remove(1);

This code removes the element at index 1 from the words list. The element "goodbye" will be removed, and the elements "hello" and "moon" will be shifted one position to the left.

Note that the remove() method can throw an IndexOutOfBoundsException if the index passed as an argument is out of bounds. You can use the size() method of the ArrayList to check the size of the list and ensure that the index is within bounds before calling the remove() method.

For example:

if (index >= 0 && index < words.size()) {
    words.remove(index);
}

This code checks that the index is greater than or equal to 0 and less than the size of the words .

Created Time:2017-11-03 00:14:44  Author:lautturi