Some people like to use for loop similar to while:
For (;;){}
Comment: This is a style that is used by some people. I personally think it is not as intuitive as while.
Whether it is ++ I or I ++
For (int I = 0; I <arrayA. Length; ++ I ){}
For (int I = 0; I <arrayA. Length; I ++ ){}
In the past, I used the I ++ method. Later, I found that many of the excellent code uses ++ I, so I switched to ++ I. I have seen some reasons for using ++, but I think those reasons are not worth mentioning.
Use I, j, and k for multi-layer Loops
For (int I = 0; I <arrayA. Length; ++ I)
{
Object [] arrayB = arrayA [I];
For (int j = 0; j <arrayB. Length; ++ j)
{
Object B = arrayB [j]; // you need to pay attention to it here. Object B = arrayB [I] will be written with no worries.
}
}
When I, j, and k are used for multi-layer loops, it is easy to make mistakes, as in the comments in the above Code. During Code Review or development, I often encounter such bugs. I once suffered a loss. Every time I, j, and k multi-layer for loops are compiled, I will remind myself, be careful, and never make mistakes!
The habit of using for is similar to that of if and while statements except for the writing of ++ I and I ++, as follows:
First Writing Method
A. There are spaces behind the keyword
B. There are spaces around the left and right of the Binary Expression.
C. Each braces occupies a single line.
D. The else keyword occupies a single row.
For (int I = 0; I <list. Count; ++ I)
{
}
Method 2:
A. There is a space behind the keyword if
B. There are spaces around the left and right of the Binary Expression.
C. Place braces on the right of the previous sentence.
For (int I = 0; I <list. Count; ++ I ){
}
Optimization is required. You may also adopt the following method:
Int listCount = list. Count;
For (int I = 0; I <listCount; ++ I ){}
If you do not add or delete the list elements in a for loop, you may get a slight improvement in performance (which may not be worth mentioning.
When you need to delete elements from the list, you may use reverse traversal. As follows:
Int listCount = list. Count;
For (int I = listCount-1; I> = 0; -- I)
{
If (condition)
{
List. RemoveAt (I );
}
}
If the implementation of list is ArrayList, reverse traversal may be better than normal deletion.
In addition, for has some other usage methods, such:
For (init (); condition (); incement ()){}
For (; I <j; ++ I, -- j ){};