In a Java program, to "process"-or, "traverse"-an array or an element in a collection, it is generally implemented with a for loop (of course, it is not possible to use other kinds of loops, but it is not known because the length of the word for is shorter, Or because the meaning of the word for is compared with this kind of operation, at this time the for loop is much more common than other loops.
For iterating over an array, this loop is generally written like this:
The traditional way to iterate through an array:
public void Additerator () {
List<string> List = new arraylist<string> ();
List List = new ArrayList ();
List.add ("AA");
List.add ("BB");
List.add ("CC");
//for (Object ls:list) {
//ls = List.get (list.size ());
for (int i=0;i<list.size (); i++) {
String ls = (string) list.get (i);
System.out.print ("added array is" +ls+ "\ n");
}
}
public void AddIterator1 () {
list<string > List = new arraylist<string> () ;
List.add ("11");
List.add ("22");
List.add ("33");
for (Object ls:list) {
System.out.print ("added array is" + ls + "\ n");
}
}
the equivalent code for a simple way to traverse collection:
public void iterator () {
List ls = new ArrayList ();
Ls.add ("AA");
Ls.add ("BB");
Ls.add ("CC");
For (Iterator i=ls.iterator (); I.hasnext ();) {
String str = (string) i.next ();
System.out.print (str+ "\ n");
}
System.out.print ("Second loop" + "\ n");
Iterator it = Ls.iterator ();
while (It.hasnext ()) {
String str = (string) it.next ();
System.out.print (str+ "\ n");
}
}
It is not always possible to define the types of objects that can be saved in collection in a Java program-they are all considered to be the most generic object objects. Until J2SE 1.5, the "Generics (generics)" mechanism was introduced, and the problem was solved. It is now possible to use collection< t> to indicate that all element types are collection of T.
For loops in Java