如何跳出递归

递归是不能通过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();
}

posted on 2019-11-11 10:23  风再起时9302  阅读(2658)  评论(0编辑  收藏  举报

导航