Java ArrayList add(int index, E element) example

來源:互聯網
上載者:User

標籤:

Simple add() method is used for adding an element at the end of the list however there is another variant of add method which is used for adding an element to the specified index.

public void add(int index, Object element)

This method adds the element at the given index.

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

Output:

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

Java ArrayList add(int index, E element) example

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.