看了部分别人的答案,自己最后还是想要总结一下。该篇文章是最好的一篇总结,在我认为。有错误的地方,还望之处。转载请告知link地址。tankyou!!
在try语句中,try要把返回的结果放置到不同的局部变量当中,执行finaly之后,从中取出返回结果,因此,即使finaly中对变量进行了改变,但是不会影响返回结果,因为使用栈保存返回值,即使在finaly当中进行数值操作,但是影响不到之前保存下来的具体的值,所以return影响不了基本类型的值,这里使用的栈保存返回值。而如果修改list,map,自定义类等引用类型时,在进入了finaly之前保存了引用的地址, 所以在finaly中引用地址指向的内容改变了,影响了返回值。
int test() {
int x = 1;
try {
x++;
returnx;
} finally {
x++;
}
}
public staticvoid main(String[] args) {
try {
Test01 test01 =new Test01();
System.out.println(test01.test());;
} catch (Exceptione) {
e.printStackTrace();
}
}
publicstatic List<String> test10(){
List<String> strlist =new ArrayList<String>();
strlist.add("zs");
strlist.add("ls");
strlist.add("ww");
strlist.add("mz");
try{
strlist.add("wq");
returnstrlist;
} finally {
strlist.add("yyy");
}
}
public staticvoid main(String[] args) {
try {
Test01 test01 =new Test01();
System.out.println(test01.test10());;
} catch (Exceptione) {
e.printStackTrace();
}
}
以上就是我的总结,如果我的总结对你有帮助,请点个赞。tankyou!!