Java如何刪除陣列中的元素?

2019-10-16 22:31:04

在Java中,如何刪除陣列元素?

範例

以下範例顯示如何從陣列中刪除元素。

package com.yiibai;

import java.util.ArrayList;

public class RemoveArrayElement {
    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]

範例2

陣列刪除的另一個範例範例

package com.yiibai;

import java.util.*;

public class RemoveArrayElement2 {
    public static void main(String[] args) {
        ArrayList<Integer> arr = new ArrayList<Integer>(5);
        arr.add(220);
        arr.add(115);
        arr.add(320);
        arr.add(145);

        System.out.println("Size of list: " + arr.size());
        for (Integer number : arr) {
            System.out.println("Number = " + number);
        }
        arr.remove(2);

        System.out.println("After remove, Size of list: " + arr.size());

        for (Integer number : arr) {
            System.out.println("Number = " + number);
        }
    }
}

執行上面範例程式碼,得到以下結果 -

Size of list: 4
Number = 220
Number = 115
Number = 320
Number = 145
After remove, Size of list: 3
Number = 220
Number = 115
Number = 145