有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是否更改函数参数的值?

这似乎是一个愚蠢的问题,但这个函数是否会影响变量bool(我将如何使用它有更大的背景,但这基本上是我不确定的)?(我是专门询问java)

void truifier (boolean bool) {
    if (bool == false) {
        bool = true;
    }
}

共 (6) 个答案

  1. # 1 楼答案

    是的,在方法的范围内。但分配方法参数有时被认为是一种不好的做法,这会降低代码的可读性并使其更容易出错。您应该考虑在方法主体内创建新的布尔变量并将参数赋值给它。p>

    此外,您的示例可以改写如下:

    if (!bool) {
        bool = true;
    }
    
  2. # 2 楼答案

    void truifier (boolean bool) {
        if (bool == false) {
            bool = true;
        }
    }
    
    void demo () {
        boolean test = false;
        truifier (test); 
        // test is still false
        System.out.println (test);
    }
    

    你知道你可以用一个文字常量来调用这个函数-这里应该修改什么

    void demo2 () {
        truifier (false); 
    }
    

    或者使用最终的局部变量

    void demo2 () {
        final boolean b = false;
        truifier (b); 
    }
    

    或者使用类中的属性:

    class X {
        private boolean secret = false; 
    
        void demo3 () {
            truifier (secret); 
        }
    }
    

    在所有这些调用中,truifier获取相关对象引用的本地副本

    boolean b = false;
    // b -> false  
    

    b是对对象“false”的引用,在本例中为原始值

    boolean c = b; 
    // c -> false, not: c-> b -> false
    c = true; 
    // c -> true
    

    c已更改,但不是b。c不是b的别名,而是引用的副本,现在该副本引用了atrue。这里只有两个真实对象(基本体):true和false

    在方法调用中,创建并传递引用的副本,对该引用所做的更改仅影响该副本。然而,没有深度复制。对于更改属性的类,将在外部更改该属性,但不能替换该类本身。或数组:可以更改数组的内容(引用副本指向同一数组),但不能更改数组本身(例如大小)。您可以在方法中更改它,但是外部引用是独立的,并且没有更改

    k = [a, b, c, d]
    l = k; 
    l [2] = z;
    // l=k=[a, b, z, d]
    l = [p, q, r]
    // k = [a, b, z, d]
    
  3. # 3 楼答案

    正如另一个响应所指出的,当作为参数传递时,将在本地为truiver函数创建一个布尔值,但对象将由位置引用。因此,根据所使用的参数类型,可以得到两种截然不同的结果

    class Foo {
        boolean is = false;
    }
    class Test
    {
        
        static void trufier(Foo b)
        {
            b.is = true;
        }
        public static void main (String[] args)
        {
            // your code goes here
            Foo bar = new Foo();
            trufier(bar);
            System.out.println(bar.is); //Output: TRUE
        }
    }
    

    但是,如果使用的不是布尔值,而是对象,则参数可以修改对象。 //此代码输出TRUE

  4. # 4 楼答案

    是的,只是在功能范围内

  5. # 5 楼答案

    原来的问题似乎是关于“参考电话”或缺乏参考电话

    为了更清楚地说明这一点,请考虑:

     void caller() {
        boolean blooean = false;
        truifier(blooean);
        System.err.println(blooean);
     }
    

    这将打印“false”

    truefier末尾的类似调用将打印“true”

  6. # 6 楼答案

    考虑一个稍微不同的例子:

    public class Test {
    
        public static void main(String[] args) {
            boolean in = false;
            truifier(in);
            System.out.println("in is " + in);
        }
    
        public static void truifier (boolean bool) {
            if (bool == false) {
                bool = true;
            }
            System.out.println("bool is " + bool);
        }
    }
    

    运行此程序的输出为:

    bool is true
    in is false
    

    bool变量将更改为true,但只要truifier方法返回,该参数变量就会消失(这就是人们说它“超出范围”的意思)。但是,传递给truifier方法的in变量保持不变