Hello Friends,
This is one of tutorials regarding the iterating Collections and Arrays. There are two ways of iterating the elements in the Collections or Arrays. One of the method is using the Iterator and another is using the advanced for loop or foreach statement. Iterator are used instead of Enumeration in Java and are used to iterate the elements in particular collection. Iterator is mostly used with the collection framework. Whereas advance for loop, introduced in JDK ver. 5, is used with collections and Arrays. It is the enhancement in the for statements, it does not include any type of counters as that of simple for loop.
However, the for-each statement cannot be used in all circumstances. Iterator cannot be used directly with array, so we have to convert the array into a collection, then use the iterator on it for iteration .Following is the code that shows the use of both in Collections and Arrays.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class PrintArray { public static void main(String args[]) { System.out.println("******Printing Collections******"); List list1 = new LinkedList(); list1.add("146"); list1.add("200"); list1.add("150"); list1.add("139"); System.out.println("using Iterator"); Iterator iter = list1.iterator(); while(iter.hasNext()) { Object element = iter.next(); System.out.print(element+","); } System.out.println("nusing for-each statement"); for(Object itrobj : list1) { System.out.print(itrobj+", "); } System.out.println("nn******Printing Arrays******"); String[] arrays = {"viru","sachin","gautam","yuvraj"}; System.out.println("using for-each statement"); for(Object obj : arrays) { System.out.print(obj+", "); } System.out.println("nusing Iterator"); List list2 = Arrays.asList(arrays); Iterator itr2 = list2.iterator(); while(itr2.hasNext()) { Object arr = itr2.next(); System.out.print(arr+","); } } } |
Hope this will help you.
Thanks,
admin@code2java.com