The difference and contact between the For loop and the Foreach loop during traversal

Source: Internet
Author: User
Tags foreach


1, the For loop and the Foreach Loop function can traverse a list, such as

for (int i = 0; i < list.size; i + +) {
    
} for
(int i = list.size (); i > 0; I-) {
    
} for
(Class C:lis T) {
}

2, however, the following case for + + and for--not universal (when the base of the loop changes, for example, the following example, two times per loop inserts an object)

Can do this


for (int i = t.size (); i > 0; I-) {
	if (i% 2 = = 0)
	  t.add (New Test ());
}

But you can't do that.

for (int i = 0; i < t.size (); i + +) {
	if (i 2 = = 0)
	  t.add (New Test ());
}

This is because, in the process of add, the value of T.size () is constantly changing, so this cardinality change can only be used--


3. For the difference between the for and foreach, the relationship of time complexity, foreach is in the constant new object out, such as the following

Package demo_20141031;

Import java.util.ArrayList;
Import java.util.Date;
Import java.util.List;

public class Test {
	private String name = "";
	
	
Public	String GetName () {
//		return name;	} public
	void SetName (String name) {
		this.name = name;
	}
	/**
	 * @param args
	 *
	/public static void main (string[] args) {
		//TODO auto-generated method stub
  
   list<test> t = new arraylist<test> ();
		Test temp = new test ();
		String a = "n";
		String B = "1";
		for (int i = 0; i <; i + +) {
			temp.setname (a);
			T.add (temp);
		}
		
		System.out.println ();		Long TIME0 = new Date (). GetTime ();
for		(int i = 0; i < t.size (); i + +) {
////		}
		Long time1 = new Date (). GetTime ();
		for (Test temps:t) {
			
		}
		long time2 = new Date (). GetTime ();		System.out.println (TIME1-TIME0);
		System.out.println (time2-time1);
	}
}

  




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.