如何跳出遞歸


遞歸是不能通過return的方式跳出的,可以通過拋異常的方式一步跳出遞歸。

例如以下遞歸找第一個攝像頭,遞歸找到后通過拋異常拋出目標結果,然后在調用的地方catch這個結果:

/**
* 遞歸找到第一個攝像頭
* <pre>
* 1.當找到攝像頭即通過拋出Exception的方式跳出遞歸,返回key
* </pre>
* @param areaVideoTreeBOList
* @return
*/
private void getFirstAreaVideoBO(List<AreaVideoTreeBO> areaVideoTreeBOList){
if(!CollectionUtils.isEmpty(areaVideoTreeBOList)){
for(AreaVideoTreeBO areaVideoTreeBO:areaVideoTreeBOList){
if(areaVideoTreeBO.getLevel() != null && areaVideoTreeBO.getLevel() == 7){
throw CommonException.exception(areaVideoTreeBO.getKey());
}else {
getFirstAreaVideoBO(areaVideoTreeBO.getChildren());
}
}
}
}

catch上面遞歸方法拋出的結果
String key = "";
try{
getFirstAreaVideoBO(areaVideoTreeBOList);
}catch (Exception e){
//跳出遞歸拋出的key
key = e.getMessage();
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM