share

Sunday, 10 May 2015

How to insert element in arraylist

we can insert element in arraylist at a given index.for this we use add(int index,element).

import java.util.ArrayList;

public class AddElement {

    public static void main(String[] args) {
       
        ArrayList<String> arr = new ArrayList<String>();
       
        // add element in arraylist
       
        arr.add("c");
        arr.add("php");
        arr.add("html");
        arr.add("java");
        arr.add("delhi");
        arr.add("INDIA");
       
        // print arraylist
       
        System.out.println("arrayList is = " + arr);
       
        /*
         * Inserts the specified element at the
         * specified position in this list
         * . Shifts the element currently at that position
         * (if any) and any subsequent elements to the right
         */
       
        arr.add(1,"javascript");
       
       // print arraylist
       
        System.out.println("after insert arrayList is = " + arr);
       
    }
}

Output:

arrayList is = [c, php, html, java, delhi, INDIA]

after insert arrayList is = [c, javascript, php, html, java, delhi, INDIA]


Related Posts: 

 


Storing Java Object In ArrayList




No comments:

Post a Comment