Searching...
Friday, 9 May 2014

Different ways to Iterate ArrayList- Example

18:37
package com.pretech;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ArrayListLoop {
	public static void main(String[] args) {
		List<String> weekdays = new ArrayList<String>();
		weekdays.add("Monday");
		weekdays.add("Tuesday");
		weekdays.add("Wednesday");
		System.out.println("ITERATE USING FOR LOOP");
		for (int num = 0; num < weekdays.size(); num++) {
			System.out.println(weekdays.get(num));
		}
		System.out.println("ITERATE USING ADVANCED FOR LOOP");
		for (String str : weekdays) {
			System.out.println(str);
		}
		
		System.out.println("ITERATE USING util.Iterator");
		Iterator<String> i = weekdays.iterator();
		while (i.hasNext()) {
			System.out.println(i.next());
		}
		
		
		System.out.println("ITERATE USING WHILE LOOP");
		int num = 0;
		while (weekdays.size() > num) {
			System.out.println(weekdays.get(num));
			num++;
		}
	}
}

Output



ITERATE USING FOR LOOP
Monday
Tuesday
Wednesday
ITERATE USING ADVANCED FOR LOOP
Monday
Tuesday
Wednesday
ITERATE USING util.Iterator
Monday
Tuesday
Wednesday
ITERATE USING WHILE LOOP
Monday
Tuesday
Wednesday


0 comments: