2. void add(int index, E element)

2. void add(int index, E element)
Inserts the specified element at the specified position in this list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
 
package com.spy.arraylist.method;
 
import java.util.ArrayList;
 
public class AddElemntThroughIndex 
{
 
	public static void main(String[] args) 
	{
 
 
	ArrayList<String> list=new ArrayList<String>();
 
	//Adding element into Arraylist
 
		list.add("Bhavesh");
 
		list.add("Abhi");
 
		list.add("vivek");
 
		list.add("milan");
 
		System.out.println("Size of Arraylist: "+list.size());
 
		for (String s : list) 
		{
 
			System.out.println(s);
		}
 
 
		//Adding elemnt at Index 1
 
		list.add(1,"Vaibhav");
 
		System.out.println("After adding elemnt at index 1");
 
		System.out.println("Size of Arraylist: "+list.size());
 
 
		for (String s : list) 
		{
 
			System.out.println(s);
		}
 
	 }
}

Output:

1
2
3
4
5
6
7
8
9
10
11
12
Size of Arraylist: 4
Bhavesh
Abhi
vivek
milan
After adding elemnt at index 1
Size of Arraylist: 5
Bhavesh
Vaibhav
Abhi
vivek
milan

Leave a Reply

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