我感兴趣地阅读了这个问题:
Can I pass parameters by reference in Java?
结果是参数(不是原语)是通过复制引用值来传递的。
正如示例所述;你不能修改你给的参数的引用:
Object o = "Hello";
mutate(o)
System.out.println(o); // Will print Hello
private void mutate(Object o) { o = "Goodbye"; } //NOT THE SAME o!
使用
final
可以避免此类问题像这样 :private void mutate(final Object o) { o = "Goodbye"; } //Compilation error
问题:
final
在这种情况下,关键字仅用于引发编译错误? final
隐含的还是强制性的? 我很少用
final
对于 Java 中的方法参数,但现在我想不出你会自愿省略放置 final
的任何情况到方法参数。谢谢!
最佳答案
为了避免这种情况:
public void searchBiggest(String startingWith) {
for (String s : collection) {
if (s.startsWith(startingWith)) {
startingWith = s;
}
}
return startingWith;
}
如您所见,它使代码不直观,因为参数可能包含与传递的值不同的值。
来自 Hard Core Java - Chapter 2 :
Little bugs like this are often the most difficult to locate. By Murphy’s Law, you can absolutely guarantee that this code will be in the middle of a huge piece of your project, and the error reports won’t directly lead you here. What’s more, you proba- bly won’t notice the impact of the bug until it goes into production and users are screaming for a fix.
You cannot afford to forget that once you write code, the story is not over. People will make changes, additions, and errors in your code. You will have to look through the code and fix everything that was messed up. To prevent this problem from occur- ring, do the following:
并且使用该参数完成了类似的示例,并使用该参数另外调用其他方法(已更改)。
关于java - 在 Java 中使用 "final"作为方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11736543/