Java.util.ArrayList 类

java.util.ArrayList.set() 方法用于将 ArrayList 中指定索引处的元素替换为指定的元素。

语法

public E set(int index, E element)

这里,E 是容器维护的元素类型。

参数

index 指定要替换的元素的索引号。
element 指定要替换的元素。

返回值

返回ArrayList指定索引处的元素.

异常

如果索引超出范围,即抛出IndexOutOfBoundsException,即(index < 0 || index > size())。

示例:

在下面的示例中,使用 java.util.ArrayList.set() 方法来替换位置处的元素ArrayList 中具有指定元素的指定索引。

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //创建ArrayList
    ArrayList<Integer> MyList = new ArrayList<Integer>();

    //填充ArrayList
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);
    MyList.add(40);
    MyList.add(50);

    System.out.println("Before method call, MyList contains: "+ MyList);
    MyList.set(1, 1000);
    System.out.println("After method call, MyList contains: "+ MyList);    
  }
}

上述代码的输出将是:

Before method call, MyList contains: [10, 20, 30, 40, 50]
After method call, MyList contains: [10, 1000, 30, 40, 50]