Java for and foreach Loops

Source: Internet
Author: User

Java for and foreach Loops

  • The variable in the for loop condition is evaluated only once! Take a look at the final picture
  • The foreach statement is newly added to Java 5. When traversing arrays and sets, foreach has good performance.
  • Foreach is a simplified for statement, but foreach cannot replace for loop. It can be said that any foreach can be rewritten as a for loop, but the opposite won't work.
  • Foreach is not a keyword in java. The loop object of foreach is generally a set, such as List, ArrayList, sorted List, Vector, and array.
  • Foreach format:

For (element type T name of each loop element O: loop object ){

// Perform O operations

}

I. Common usage methods.

  • Foreach traverses the List.
  • Ii. Limitations.

    Although foreach can traverse arrays or sets, it can only be used for traversing and cannot modify arrays or sets during traversal, the for loop can modify the source array or set during traversal.

  • Set
  • Special attention !!

     

    Related Article

    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.