Use of enhanced for loop in Java

Source: Internet
Author: User

This method does not appear until after jdk1.5.

1: iterating through an array

Grammar:

for (Type Value:array) {

Expression value;

}

Example:

void Sum ()

{

Int[] array = {1,2,5,8,9};

int sum= 0;

for (int n:array)

{

sum+= N;

}

Disadvantages:
For arrays, it is difficult to access subscript values;

2: Traversing the collection

Grammar:

for (Type value:iterable) {

Expression value;

}

Example:

    void Sum ()

{

List List = new ArrayList ();

List.add ("Hello");

List.add ("Java");

List.add ("world!");

String s = "";

for (Object o:list)

{

String temp = (string) o;

s + = temp;

}

    

The code above will be translated by the compiler to:

void SomeFunction ()

{

List List = new ArrayList ();

List.add ("Hello");

List.add ("Java");

List.add ("world!");

String s = "";

for (Iterator iter = List.iterator (); Iter.hasnext ();)

{

String temp = Iter.next ();

s + = temp;

}

For traversing a collection, it is not good to delete the contents of the collection (because it is internally called Interator) compared to using Interator.
It is not recommended to use an enhanced for loop in addition to simply traversing and reading the contents of it.

Use of enhanced for loop 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.