SoFunction
Updated on 2025-03-08

Count the pitfalls in the java for loop

1. Several syntaxes for loop statements

grammar:

for loop format: for (initialization statement; conditional judgment; progressive statement) { loop body; } while loop format: initialization statement; while (conditional judgment) { loop body; progressive statement; } do-while loop format: initialization statement; do{ loop body; progressive statement; } while (conditional judgment);

Example:

package ;
import ;
import ;
/**
 * Loop format
 * @author Coriander
 */
public class Format {
   public static void main(String[] args) {
       List<Integer> numList = new ArrayList<>();
       (1);
       (2);
       // for format       ("=======for Format====");
       int size = ();
       for (int i = 0; i < size; i++) {
           int num = (i);
           (num);
      }
       ();
       // Enhanced for       ("=======Enhancedfor Format====");
       for (Integer num : numList) {
           (num);
      }
       ();
       // while
       ("=======while Format====");
       int i = 0;
       while (i < size){
           int num = (i);
           (num);
           i++;
      }
       // do while
       ();
       ("=======do while Format====");
       int j = 0;
       do{
           int num = (j);
           (num);
           j++;
      }while (j < size);
  }
}

2. Points to be noted in the loop

As a server development, you need to pay attention to the performance of the server during development. After all, there are thousands of clients and only one server, and the performance of crushing the server is necessary. As a developer on the server, you must also be able to save a little bit and summarize the attention points of the cycle.

2.1 If the loop meets the search needs, break directly and do not waste performance

   public static void main(String[] args) {
       int size = 1000;
       for (int i = 1;i<size;i++){
           if ( i == 10){
               doSomeThing();
               // Here you should break directly and end the loop as soon as possible          }
      }
  }

2.2 When you can use for each collection, try to use for each.

 for (Integer num : numList) {
           (num);
      }

Reason: Unnecessary operation indexing to avoid errors and clear code.

2.3 Don't write an empty dead loop

public static void main(String[] args) {
       while (true){
           // doNothing()
      }
  }

Reason: The garbage code is deleted early, which poses a security risk.

2.4 Do not new objects in loops

   public static void main(String[] args) {
       int size = 1000;
       for (int i = 1;i<size;i++){
           Date date = new Date();
      }
  }

Reason: Frequent creation of objects in a loop, and the creation and recycling of large amounts of object memory will increase the system burden.

2.5 It can be done outside the loop, do not put it in the loop

public static void main(String[] args) {
   int size = 1000;
   for (int i = 1;i<size;i++){
       int nowSec = getNowSec();
  }
}

Reason: NowSec can obviously be calculated and saved outside the loop and placed inside the loop to calculate, which wastes performance and is not easy to understand the code. Similar code is often seen during the code review process. This is a code that is not careful in development or copied, and is placed in a loop without any brainstorm.

2.6 Circulation suggestions

While loop is used to limit the upper limit and make a large threshold count. If it exceeds the alarm directly

For loops are used for any scenario with a certain number of times; otherwise, while loops are used more often.

3. The pit in the cycle

3.1 byte causes a dead loop

   public static void main(String[] args) {
       int size = 1000;
       for (byte i = 1;i<size;i++){
           (i);
      }
  }

Cause analysis: byte will cross the boundary and return to negative numbers during execution, which will cause a dead loop. Some newbies do not pay attention to this in development, which leads to this situation in previous games. You must pay attention! !

3.2 Operating the index in reverse in a loop causes a dead loop

   public static void main(String[] args) {
       int size = 1000;
       for (int i = 1;i&lt;size;i++){
           if ( A certain condition){
               i--;
          }
      }
  }

Cause analysis: Reverse operation index causes fallback. You must be alert to this situation during development. It is best not to have such operations in the code. careful

3.3 Do not remove/add operations of elements in the loop when operating the collection

public static void main(String[] args) {
       List<Integer> list = new ArrayList();
       (1);
       (2);
       (3);
       (4);
       (5);
       (6);
       for (int i : list) {
           if(i == 4)(99);
           (i);
      }
  }

Cause analysis: For the traversal of the collection, the enhanced for loop is actually implemented internally through an iterator. Modification is not allowed during iteration, otherwise a ConcurrentModificationException exception will be thrown.

If you need to delete it in the collection, you can use an iterator.

Iterator it=();
       while(()){
           Object e=();
           if("b".equals(e)){
               ();
          }
      }

3.4 Do not access the database multiple times in a loop, redis

public static void main(String[] args) {
       int size = 1000;
       for (int i = 1;i&lt;size;i++){
           // Query the database           // Query redis      }
  }

Cause analysis: Querying the database multiple times will cause excessive pressure on the database and also cause program blockage. You can use batch query.

4. Summary

That’s all for this article. I hope it can help you and I hope you can pay more attention to more of my content!