原文: https://beginnersbook.com/2013/12/java-arraylist-addint-index-e-element-example/

简单的add()方法用于在列表的末尾添加元素,但是add方法的另一种变体用于向指定的索引添加元素。

public void add(int index, Object element)

此方法在给定索引处添加元素。

  1. package beginnersbook.com;
  2. import java.util.ArrayList;
  3. public class AddMethodExample {
  4. public static void main(String[] args) {
  5. // ArrayList of String type
  6. ArrayList<String> al = new ArrayList<String>();
  7. // simple add() methods for adding elements at the end
  8. al.add("Hi");
  9. al.add("hello");
  10. al.add("String");
  11. al.add("Test");
  12. //adding element to the 4th position
  13. //4th position = 3 index as index starts with 0
  14. al.add(3,"Howdy");
  15. System.out.println("Elements after adding string Howdy:"+ al);
  16. //adding string to 1st position
  17. al.add(0, "Bye");
  18. //Print
  19. System.out.println("Elements after adding string bye:"+ al);
  20. }
  21. }

输出:

  1. Elements after adding string Howdy:[Hi, hello, String, Howdy, Test]
  2. Elements after adding string bye:[Bye, Hi, hello, String, Howdy, Test]

参考

ArrayList.add(int,E)(int, E))