简单的add()
方法用于在列表的末尾添加元素,但是add
方法的另一种变体用于向指定的索引添加元素。
public void add(int index, Object element)
此方法在给定索引处添加元素。
例
package beginnersbook.com;
import java.util.ArrayList;
public class AddMethodExample {
public static void main(String[] args) {
// ArrayList of String type
ArrayList<String> al = new ArrayList<String>();
// simple add() methods for adding elements at the end
al.add("Hi");
al.add("hello");
al.add("String");
al.add("Test");
//adding element to the 4th position
//4th position = 3 index as index starts with 0
al.add(3,"Howdy");
System.out.println("Elements after adding string Howdy:"+ al);
//adding string to 1st position
al.add(0, "Bye");
//Print
System.out.println("Elements after adding string bye:"+ al);
}
}
输出:
Elements after adding string Howdy:[Hi, hello, String, Howdy, Test]
Elements after adding string bye:[Bye, Hi, hello, String, Howdy, Test]