Skip to content

Latest commit

 

History

History
48 lines (36 loc) · 1.52 KB

File metadata and controls

48 lines (36 loc) · 1.52 KB

Java ArrayList add(int index, E element)

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

简单的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]

参考

[ArrayList.add(int,E)](https://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#add(int, E))