For loops in Java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.