日期:2014-05-20  浏览次数:20681 次

一个有关静态方法的问题

package test4;

public class Test {

public static void data(int x , int y) {
x = 4;
y = 5;
}

public static void data(Integer x , Integer y) {
x = 8;
y = 9;
}

public static void data(String s) {
s = new String("world");
}

public static void main(String[] args) {
int a = 2;
int b = 3;

data(a,b);

System.out.println(a);
System.out.println(b);

Integer c = 2;
Integer d = 3;

data(c,d);

System.out.println(c);
System.out.println(d);

String s = "hello";

data(s);

System.out.println(s);

}

}

这个程序的输出是:
2
3
2
3
hello
这显然和我预料的输出:
2
3
8
9
world
不一样,求高手解答

------最佳解决方案--------------------
还是老问题。
方法内的是局部变量,局部变量的变化不会影响传入到方法的参数的值。

------其他解决方案--------------------
这个跟java变量的传递类型有关系,java只有值传递这一种类型,不存在引用传递(好像c语言,有这个,不清楚)。通过希望通过方法改变变量的引用,显然是不可行的,也是错误的。
------其他解决方案--------------------
你看一下这个代码:
public class TestStatic {
     
    public static void data(int x , int y) {
        x = 4;
        y = 5;
 System.out.println(x);
        System.out.println(y);
    }
     
    public static void data(Integer x , Integer y) {
        x = 8;
        y = 9;
 System.out.println(x);
        System.out.println(y);
    }
     
    public static void data(String s) {
        s = new String("world");
        System.out.println(s);
    }
     
    public static void main(String[] args) {
        int a = 2;
        int b = 3;
         
        data(a,b);
         
        System.out.println(a);
        System.out.println(b);
         
        Integer c = 2;
        Integer d = 3;
         
        data(c,d);
         
        System.out.println(c);