Java ArrayList add(int index, E element) example

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]

转载于:https://www.cnblogs.com/hust-ghtao/p/4658375.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值