如何在 Java 中移除数组元素



问题描述

如何移除数组中的元素?

解决方案

以下示例展示了如何从数组中移除元素。

import java.util.ArrayList;

public class Main {
   public static void main(String[] args) {
      ArrayList objArray = new ArrayList();
      objArray.clear();
      objArray.add(0,"0th element");
      objArray.add(1,"1st element");
      objArray.add(2,"2nd element");
      System.out.println("Array before removing an element"+objArray);
      objArray.remove(1);
      objArray.remove("0th element");
      System.out.println("Array after removing an element"+objArray);
   }
}

结果

上面的代码示例将生成以下结果。

Array before removing an  element[0th element, 1st element, 2nd element]
Array after removing an element[2nd element]

数组移除的另一个示例示例

import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String[] args) {
      ArrayList<Integer> arr = new ArrayList<Integer>(5);
      arr.add(20);
      arr.add(15);
      arr.add(30);
      arr.add(45);
      
      System.out.println("Size of list: " + arr.size());
      for (Integer number : arr) {
         System.out.println("Number = " + number);
      } 
      arr.remove(2);
      System.out.println("Now, Size of list: " + arr.size());
      
      for (Integer number : arr) {
         System.out.println("Number = " + number);
      } 
   }
}   

上面的代码示例将生成以下结果。

Size of list: 4
Number = 20
Number = 15
Number = 30
Number = 45
Now, Size of list: 3
Number = 20
Number = 15
Number = 45
java_arrays.htm
广告