Java 中的 set(int, obj o) 方法有什么作用?
ArrayList 类的 set() 方法使用指定的元素替换该列表中指定位置处的元素。
示例
import java.util.ArrayList; public class Sample { public static void main(String args[]) { ArrayList al = new ArrayList(); System.out.println("Initial size of al: " + al.size()); al.add("C"); al.add("A"); al.add("E"); al.add(1, "A2"); System.out.println("Size of al after additions: " + al.size()); System.out.println("Contents of al: " + al); System.out.println("Size of al after deletions: " + al.size()); System.out.println("Contents of al: " + al); al.set(2, "new"); System.out.println("Contents of al after setting the element: " + al); } }
输出
Initial size of al: 0 Size of al after additions: 4 Contents of al: [C, A2, A, E] Size of al after deletions: 4 Contents of al: [C, A2, A, E] Contents of al after setting the element: [C, A2, new, E]
广告