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,
Send love - A little romance for programmers VHDL—— Design of frequency divider Python Implementation of Hanoi Tower code It's over , Starting salary 30khtml+css+js Make a simple website home page QQ Login interface implementation Hill sorting of sorting algorithm ——c++ realization 【 Wechat applet learning 】 Netease music cloud code page implementation details Resume the 13th session python Blue Bridge Cup 2022 Solution to the 13th Blue Bridge Cup ( whole )