Java Background Development Interview __java

Source: Internet
Author: User

Interview Question: What is the difference between for and foreach in Java? When do you use for? When will you use foreach?

After Java 5, Java provides another simpler loop: The Foreach loop, which iterates through arrays and collections more concisely. When you iterate through arrays and collection tuples using a foreach loop, you do not need to get the length of the array and the collection to access the array elements and the collection elements based on the index, and the Foreach loop automatically iterates through the array and each element of the collection.

one, common use way

1. Foreach Traversal array

The public class foreachtest{public
  static void Main (string[] args) {
    string[] books = {"Java", "C + +", "C"};
    for (String book:books) {
      System.out.println (book);}}}
   

2. foreach Traverse list

public class foreachtest{public
  static void Main (string[] args) {
    list<string> List = new arraylist< String> ();
    List.add ("Java");
    List.add ("C + +");
    List.add ("C");
    for (String str:list) {
      System.out.println (str);}}}
   

As you can see from the above program, you do not need to get array lengths to iterate through an array element (or collection Element) using a foreach loop, nor do you need to access an array element (or a collection element) based on an index.

The Foreach loop differs from the ordinary loop in that it does not need to cycle the conditions without iterating over the statements, which are all performed by the system, and the Foreach loop automatically iterates through each element of the group (or set), and when each tuple is iterated, the Foreach loop ends automatically.

Second, limitations
foreach can traverse an array or a collection, but it can only be traversed, unable to modify the array or collection during the traversal process, and the For loop can be modified by an array or set during traversal.

1. Array

public class foreachtest{public
  static void Main (string[] args) {
    string[] books = {"Java", "C + +", "C"};
    foreach for
    (String book:books) {book
        = "Python";
    }
    System.out.println ("foreach:" + arrays.tostring (books));
    For for
    (int i = 0; i < books.length i++) {
         books[i] = "Python";
    }
   System.out.println ("for:" + arrays.tostring (books));
  }

Output

Foreach:[java, C + +, C]
For:[python, python, Python]

2. Collection

public class foreachtest{public
  static void Main (string[] args) {
    list<string> List = new arraylist< String> ();
    List.add ("Java");
    List.add ("C + +");
    List.add ("C");
    foreach for
    (String str:list) {
        str = ' Python ';
    }
    System.out.println ("foreach:" + arrays.tostring (List.toarray ()));
    for for (int i = 0; i < list.size (); i++) {
        List.set (i, "Python");
    }
    System.out.println ("for:" + arrays.tostring (List.toarray ()));
  }
   

Output

Foreach:[java, C + +, C]
For:[python, python, Python]

summarized as follows:
1, if only traversing the array or the elements of the collection, with a foreach loop;
2. If you want to modify an array or an element in a collection, use a For loop.
3. Foreach cannot use subscript to access each element, so it cannot be used for complex operations such as additions, deletions, and so on.
4, the foreach statement is a special version of the For statement, but the foreach statement does not completely replace the for statement.

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.