beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java ArrayList add(int index, E element) example

By Chaitanya Singh | Filed Under: Java Collections

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

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);
   }
}

Output:

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

Reference

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

Enjoyed this post? Try these related posts

  1. Java ArrayList isEmpty() Method example
  2. How to get the size of TreeMap example – Java
  3. How to sort HashMap in Java by Keys and Values
  4. Vector ListIterator example in Java
  5. How to clone an ArrayList to another ArrayList
  6. Java – Convert Vector to ArrayList example

Comments

  1. Enamul Haque says

    August 22, 2014 at 4:47 AM

    Thank For developing The nice Site.
    It is helpful every method description with example.
    Thanks Again as a java developer.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

ArrayList Tutorial

  • Java ArrayList

Java ArrayList Methods

  • add(Object obj)
  • add(int index, Object element)
  • addAll(Collection c)
  • addAll(int index, Collection c)
  • contains()
  • get()
  • indexOf()
  • ensureCapacity()
  • isEmpty()
  • lastIndexOf()
  • remove()
  • remove(Object obj)
  • trimToSize()
  • set()
  • clone()
  • clear()
  • size()

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap