The following code shows how to get Size of ArrayList and loop through elements.
/* w w w. j av a 2 s . com*/ import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add("1"); arrayList.add("2"); arrayList.add("3"); arrayList.add("java2s.com"); int totalElements = arrayList.size(); for (int index = 0; index < totalElements; index++) System.out.println(arrayList.get(index)); } }
The code above generates the following result.
The following code shows how to traverse through ArrayList in forward direction using ListIterator.
//from w w w .jav a 2s . com import java.util.ArrayList; import java.util.ListIterator; public class Main { public static void main(String[] args) { ArrayList<String> aList = new ArrayList<String>(); aList.add("1"); aList.add("2"); aList.add("3"); aList.add("4"); aList.add("java2s.com"); ListIterator listIterator = aList.listIterator(); while (listIterator.hasNext()){ System.out.println(listIterator.next()); } } }
The code above generates the following result.
The following code shows how to get the size of an arraylist after and before add and remove methods.
//from w ww . ja v a 2s . c o m import java.util.ArrayList; public class Main { public static void main(String args[]) { ArrayList<String> al = new ArrayList<String>(); System.out.println("Initial size of al: " + al.size()); al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); al.add(1, "java2s.com"); System.out.println("Size of al after additions: " + al.size()); System.out.println("Contents of al: " + al); al.remove("F"); al.remove(2); System.out.println("Size of al after deletions: " + al.size()); System.out.println("Contents of al: " + al); } }
The code above generates the following result.
The following code shows how to use set method to change the value in an array list.
//from w ww.j a v a2 s. c o m import java.util.ArrayList; public class Main { public static void main(String[] a) { ArrayList<String> nums = new ArrayList<String>(); nums.clear(); nums.add("One"); nums.add("Two"); nums.add("Three"); System.out.println(nums); nums.set(0, "Uno"); nums.set(1, "Dos"); nums.set(2, "java2s.com"); System.out.println(nums); } }
The code above generates the following result.