adding number to an arraylist in java code example
Example 1: ArrayList addAll(int index, Collection c) method in java
import java.util.ArrayList;
public class ArrayListAddAllMethod
{
public static void main(String[] args)
{
ArrayList<Integer> al1 = new ArrayList<Integer>(5);
al1.add(11);
al1.add(13);
al1.add(15);
System.out.println("ArrayList 1 elements: ");
for(Integer number : al1)
{
System.out.println("Number: " + number);
}
ArrayList<Integer> al2 = new ArrayList<Integer>(5);
al2.add(12);
al2.add(14);
al2.add(16);
al2.add(18);
System.out.println("ArrayList 2 elements: ");
for(Integer number : al2)
{
System.out.println("Number: " + number);
}
al1.addAll(2, al2);
System.out.println("Print all elements: ");
for(Integer number : al1)
{
System.out.println("Number: " + number);
}
}
}
Example 2: how to add to an arraylist java
import java.util.ArrayList;
public class Details {
public static void main(String[] args) {
ArrayList<String> al= new ArrayList<String>();
al.add("Ram");
al.add("Shyam");
al.add("CPS");
al.add("John");
al.add("Steve");
System.out.println("Elements of ArrayList of String Type: "+al);