「已注销」 2010-10-14 14:03
浏览 416
已采纳

源自一个面试的问题:字符串在函数的参数中是当成值传递还是引用传递。

源自一个面试的问题:字符串在函数的参数中是当成值传递还是引用传递。

这是测试方法:

public void setA(String a)
{
    System.out.println("In the setmethod before set:#### " + a);
    a = "I am a student";
    System.out.println("In the setmethod after set:#### " + a);
}

public static void main(String[] args)
{
    String a = "China is our motherland";
    System.out.println("Out before set:----- "+ a);
    new UserQuery().setA(a);
    System.out.println("Out after set:----- "+a);
}

结果显示
Out before set:----- China is our motherland
In the setmethod before set:#### China is our motherland
In the setmethod after set:#### I am a student
Out after set:----- China is our motherland

这样的话,如果要在一个方法里面修改传入的参数的值,岂不是不行?如果这样的该怎么办呢?

  • 写回答

2条回答 默认 最新

  • iteye_3976 2010-10-15 16:50
    关注

    a = "I am a student";
    是创建了一个新的对象的

    如果要实现你说的,改变字符串,那就下面两种方法:
    1。传进来的时候就不要传String,传StringBuffer。因为String是final的
    2。传进来一个对象,你的a,b,c,d,e是对象的属性,然后改变对象的属性,就可以了

    还有和2类似的,就是传进来数组,然后得到结果后解析数组得到结果,比建立类稍微简单一点点

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?