将对象和字符串文字作为参数传递 [英] Passing object and string literal as parameters

查看:105
本文介绍了将对象和字符串文字作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Main {
static void m (int[] i) {
i[0] += 7;
}
public static void main (String[] args) {
int[] j = new int[1];
j[0] = 12;
m(j);
System.out.println(j[0]);
}
}





输出

19



这里j和i指向相同的地址,因此我也改变了值。



我尝试了什么:





output
19

Here j and i points to the same address so the value gets changed for i too.

What I have tried:

class Main {
static void m (int i) {
i += 7;
}
public static void main (String[] args) {
int j;
j= 12;
m(j);
System.out.println(j);
}
}





输出

12









output
12



class Main{
static void m(String s1) {
s1=new String("acting");

}
public static void main(String[] args) {
String s2 = new String("action");
m(s2);
System.out.println(s2);
}
}





输出

行动



这里将为s1和s2创建单独的内存,所以这个输出对我来说很有意义。





output
action

here separate memory will be created for s1 and s2 so this output makes sense for me.

class Main{
static void m(String s1) {
s1="acting";

}
public static void main(String[] args) {
String s2 ="action";
m(s2);
System.out.println(s2);
}
}





输出

行动



但是这里的字符串文字将指向同一个位置,然后s2的值也不会改变。任何人都可以清楚地解释我吗?



output
action

But here the string literals will be pointing to the same location and then too the value of s2 is not changed. Could anyone explain me clearly?

推荐答案

见这里: Java方法参数 [ ^ ]。


使用Java,所有参数都按值传递。这意味着函数在传递像字符串这样的对象时会获得原始引用的副本。因为字符串是不可变对象(The Java™Tutorials> Essential Classes> Concurrency) [ ^ ],一个新字符串在原始文件保持不变的情况下创建并分配给引用的副本。



但是当使用数组时,引用的副本不变(仍然相同)值作为原始)以便可以更改数组项。



另请参阅SO线程 c - 在Java中通过引用传递字符串? - Stack Overflow [ ^ ]还提供了修改作为函数参数传递的字符串的解决方案。
With Java, all paramters are passed by value. That means a function gets a copy of the original reference when passing objects like strings. Because strings are Immutable Objects (The Java™ Tutorials > Essential Classes > Concurrency)[^], a new string is created and assigned to the copy of the reference while the original is left unchanged.

But when using an array, the copy of the reference is unchanged (still the same value as the original) so that array items can be changed.

See also the SO thread c - Passing a String by Reference in Java? - Stack Overflow[^] which also provides solutions to modify a string passed as function parameter.


这篇关于将对象和字符串文字作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆