乐闻世界logo
搜索文章和话题

How to Remove last object of ArrayList in Java

1个答案

1

In Java, to remove the last element from an ArrayList, you can use the remove() method. The ArrayList class provides several overloaded remove() methods, with two of the most commonly used being removal by index and removal by object. For removing the last element, we typically use the index-based approach because it allows direct access to the final element.

Steps

  1. Ensure the ArrayList is not empty to prevent IndexOutOfBoundsException.
  2. Obtain the index of the last element using size() - 1.
  3. Use the remove(int index) method to delete the element at this index.

Example Code

java
import java.util.ArrayList; public class Main { public static void main(String[] args) { // Create an ArrayList and add some elements ArrayList<String> list = new ArrayList<>(); list.add("Java"); list.add("Python"); list.add("C++"); // Check if the list is empty if (!list.isEmpty()) { // Remove the last element list.remove(list.size() - 1); } // Output the modified ArrayList System.out.println(list); // Output [Java, Python] } }

In this example, we first create an ArrayList containing three strings. We calculate the index of the last element using list.size() - 1 and remove it via the remove() method. Before deletion, we verify that the list is not empty, which is a good practice to avoid runtime errors.

This approach is a simple and effective way to remove the last element from an ArrayList.

2024年6月29日 12:07 回复

你的答案