-1

可能重复:
Java、按值传递、引用变量

考虑以下简单的 java 程序

class main{
          public static void main(String args[]){
                int x = 5;
                change(x);
                System.out.println(x);
          }
          static void change(int x){
             x = 4;
          }
 }

由于java使用按值传递,x的值不会在主中改变..为了克服这个问题,我们在c中有通过引用传递的概念..但是我在java中没有找到任何这样的概念..我怎么能真的改变 x.. 的值?如果没有办法改变 x 那么这不是 java 的缺点吗?

4

5 回答 5

2

You can't change the value of x in the calling code within change. (It would have been clearer if you'd used two different variable names.) I don't find it makes my life harder in Java - you can use pass by reference in C#, but it's rarely a good idea.

Pass by value is usually easier to understand, and leads to simpler code. Usually I either want a method to simply compute something - in which case that should be the return value - or I want to mutate an object; preferably the object I call the method on, but potentially an object which I indicate by passing a reference by value for one of the parameters. I very, very rarely wish I could change the value of a variable in the calling code other than by using simple assignment.

(Oh, and C doesn't have pass-by-reference either, by the way. It allows you to pass pointers by value, but that's not the same thing.)

于 2011-11-06T21:22:03.273 回答
0

一种方法是通过将声明移到主函数之外来赋予 x 类范围,这样它的范围对类的所有成员都可用,包括函数更改。您还可以将 x 设为公共、受保护或公共类的成员。

class main{
      int x = 5;
      public static void main(String args[]){
            change(x);
            System.out.println(x);
      }
      static void change(int x){
         x = 4;
      }
}

所以所有对象的默认私有范围并不是一个缺点,恰恰相反。除非程序员明确允许,否则它可以最大限度地减少意外更改的副作用。

于 2011-11-06T21:34:51.610 回答
0

C 也按值传递参数。但是,如果您传递一个指针(也可以通过指针的值),您可以更改指针指向的变量的值。

您可以通过更改函数中指针的值来检查 C 是否按值传递指针。当函数返回时,指针仍然指向同一个位置(不是它在函数中指向的位置)。

传递一个值并不是一个缺点。如果我确定一个函数或方法不能改变参数的值,我会觉得更安全。

如果要更改 的值x,请使用以下代码:

x = change(x);

并更改void change(...)int change(...).

于 2011-11-07T04:44:33.807 回答
0

if you need to change a value using a method then don't use primitive data types...alternatively since you are using an int you could do this:

 class main{
          public static void main(String args[]){
                int x = 5;
                x = change(x);
                System.out.println(x);
          }
          static int change(int x){
             x = 4;
             return x;
          }
 }
于 2011-11-06T21:24:44.243 回答
-2

Basically primitives are passed by value, objects are passed by reference and there are no pointers. So make a wrapper class or return the new value.

More information can be found here: http://javadude.com/articles/passbyvalue.htm

于 2011-11-06T21:22:03.780 回答