1ArrayList<String> arrayList = new ArrayList<>();
2// Adds element at the back of the list
3arrayList.add("foo");
4arrayList.add("bar");
5// Result = ["foo", "bar"]
6
7// Adds element at the specified index
8arrayList.add(1, "baz");
9// Result = ["foo", "baz", "bar"]
1import java.util.ArrayList;
2public class ArrayListAddMethodExample
3{
4 public static void main(String[] args)
5 {
6 // creating an empty ArrayList with initial capacity
7 ArrayList<Integer> al = new ArrayList<Integer>(6);
8 al.add(12);
9 al.add(14);
10 al.add(16);
11 al.add(18);
12 al.add(20);
13 // adding element 15 at fourth position
14 al.add(3, 15);
15 for(Integer number : al)
16 {
17 System.out.println("Number: " + number);
18 }
19 }
20}
1/* add(index, item to add); */
2ArrayList<String> languages = new ArrayList<String>();
3languages.add("PHP");
4languages.add("JAVA");
5languages.add("C#");
6languages.add(2, "RUBY"); /* at index 2, add RUBY*/
7ArrayList<int> numbers = new ArrayList<int>();
8numbers.add(9);
9numbers.add(14);
10numbers.add(2);
11numbers.add(1, 15); /* at index 1, add 15*/
12/*
13 After Execution:
14 languages => PHP JAVA RUBY C#
15 numbers => 9 15 14 2
16*/
1//Insert a value by using arrayName.add(index, value)
2//Will not remove current element at index. Will simply move all elements to
3//the right.
4import java.util.ArrayList;
5public class main{
6 public static void main(String[] args){
7 ArrayList<Integer> list = new ArrayList<Integer>();
8 list.add(0);
9 list.add(1);
10 list.add(2);
11 list.add(3);
12 list.add(4);
13 list.add(5);
14 list.add(0, 100);
15
16 //enhanced for loop will print all elements of the ArrayList
17 for(int element : list){
18 System.out.print(list + ", ");
19 }
20 //Expected output: "100, 0, 1, 2, 3, 4, 5, "
21 }
22
23}