java - 在 Java 中使用 "final"作为方法参数

标签 java methods parameters final

我感兴趣地阅读了这个问题:
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/

    相关文章:

    java - 检查 Realm 对象是否有任何变化

    java - 查找数据集中的 Top-K 记录

    java - 在java中查找和删除重复项时出错

    java - 如何通过名称调用 getter 方法?

    java - 如何使用 Spring Actuator 在浏览器屏幕中显示日志文件的内容?

    java - 从 html 字符串中删除字体颜色

    c# - Tamarin Studio中出现关于 “Cannot Declare Instance Members in Static Class”的错误消息

    c# - 如何在设置类型等方法中设置参数

    c - 如何从带有指针的函数返回数组

    parameters - Informatica Workflow 无法读取参数文件