First of all, distinguish between stack overflow and heap overflow :

We know that there are references to object calls in the method stack , The stack has a certain depth ( length ) Of , If the recursive call exceeds the depth of the stack, the stack overflow will be triggered .

And heap memory holds new Who came out , If the heap memory area is full, it will cause a memory overflow

Take a scene , We're traversing sdcard Recursion is used for files , Here, if the file path is deep, the stack overflow is likely to occur , The solution to this problem is also simple , It doesn't have to be recursive , Change to cycle .

Let's first look at our normal recursive operations :
public static void RecursiveTraversal(String path){ File file = new
File(path); file[] files = file.listFile();if(files == null){ return; } int
length = files.length();for(int i=0; i < length; i++){ if
(files[i].isDirectory()){// Recursive call RecursiveTraversal(files[i].getAbsolutePath());
}else { //do other... } } }
Then we don't need recursion , Use a loop instead to handle the following :
public static void RecursiveTraversal(String path){ List<File> fileList = new
ArrayList<File>(); fileList.add(new File(path)); while(!fileList.isEmpty()){
File file = fileList.remove(0); file[] files = file.listFile(); if(files == null
){return; } int length = files.length(); for(int i=0; i < length; i++){ if
(files[i].isDirectory()){// Add the file that needs to be traversed again to list in fileList.add(files[i]); } else {
//do other... } } } }

First add the file to be traversed list in , And then traverse this list, If the file is a directory, continue adding to list, Remove non catalog files , It's not going to stop cycling list, Until you know there's no element , The stack overflow problem is successfully avoided .

©2019-2020 Toolsou All rights reserved,
One is called “ Asking for the train ” A small village Finally got the train SparkSQL Achieve partition overlay write Character recognition technology of vehicle license plate based on Neural Network c++ Memory Pointer out of bounds detection mechanism _CrtMemBlockHeade Change one's mind ! Tesla starts to deliver made in China to European market Model 3Qt study 7—— Modal and modeless dialog boxes JavaScript Medium Call and ApplyJAVA Convert a string to a numeric type k8s Entry to give up --k8s Key concepts Count the number of letters (java Language implementation )