This java example shows how to display all elements in a Java ArrayList object using get method,Iterator , ListIterator and for-each loop.
import java.util.ArrayList; import java.util.Iterator; import java.util.ListIterator; public class DisplayAllElementsInArrayListExample { public static void main(String[] args) { // create an ArrayList object ArrayList arrayList = new ArrayList(); // Add elements to Arraylist arrayList.add("1"); arrayList.add("2"); arrayList.add("3"); System.out.println("Arraylist contains : "); System.out.println("Display elements using get method."); for (int i = 0; i < arrayList.size(); i++) System.out.println(arrayList.get(i)); System.out.println("Display elements using Iterator."); Iterator i = arrayList.iterator(); while (i.hasNext()) { System.out.println(i.next()); } System.out.println("Display elements using ListIterator."); ListIterator listi = arrayList.listIterator(); while (listi.hasNext()) { System.out.println(listi.next()); } System.out .println("Display elements using for-each loop(available since jdk1.5)"); for (Object e : arrayList) { System.out.println(e); } } }
The output is:
Arraylist contains :
Display elements using get method.
1
2
3
Display elements using Iterator.
1
2
3
Display elements using ListIterator.
1
2
3
Display elements using for-each loop(available since jdk1.5)
1
2
3
No comments:
Post a Comment