dzi*_*iki 1 java if-statement return
我有这样的代码:
private final Something (SomethingElse nimportant)
List list = (List) mListOfSomething.get(SOME_ENUMS);
if (list == null)
// dont ask me why not list.isEmpty(), I'm not the author of this code)
list = new ArrayList();
if (transaction.getPartner() instanceof IAnotherSomething) {
IAnotherSomething ias = (IAnotherSomething) transaction.getPartner();
return ias.getContract().next();
}
// NIMPORTANT code ommited, produces boolean "something"
if (something) {
// something happens
list.add(contract)
}
if (!something) {
// something else happens
list.add(contract)
}
}
return (IContract) list.get(0);
}
Run Code Online (Sandbox Code Playgroud)
我有一个脑力劳动 - 如果列表为空,(或== null)并且这个if语句(transaction.getPartner() instanceof IAnotherSomething)为真,方法应该在这个if语句上退出并且应该返回ias.getContract().next()- 或者我错了吗?
return语句结束方法的执行,将指定的值返回给方法的调用者,无论它放在方法中的什么位置.它是否在"复杂的if语句"中并不重要.
这是一些特殊情况,其中return语句不是该方法中执行的最后一个语句:
return语句包含在包含finally块的try子句中,该子句将在从方法返回之前执行.
return语句包含在try子句中,并且要返回的表达式的求值会抛出一个由catch块捕获的异常,该异常将被执行(并且必须具有return语句或抛出异常).