Java 集合 ArrayList add(int index, E element)

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程