Java ArrayList remove()方法

java.util.ArrayList.remove(int index) 该方法用于从ArrayList中移除指定索引的元素。

1 语法

public E remove(int index)

2 参数

index:要删除的元素的索引。

3 返回值

返回ArrayList中删除的元素。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.util.ArrayList.remove(int index)方法的例子
 */
import java.util.ArrayList;

public class Demo {

    public static void main(String[] args) {

        // create an empty array list with an initial capacity
        ArrayList<Integer> arrlist = new ArrayList<Integer>(5);

        // use add() method to add elements in the deque
        arrlist.add(20);
        arrlist.add(15);
        arrlist.add(30);
        arrlist.add(45);

        System.out.println("Size of list: " + arrlist.size());

        // let us print all the elements available in list
        for (Integer number : arrlist) {
            System.out.println("Number = " + number);
        }

        // Removes element at 3rd position
        arrlist.remove(2);

        System.out.println("Now, Size of list: " + arrlist.size());

        // let us print all the elements available in list
        for (Integer number : arrlist) {
            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

 

热门文章

优秀文章