class Effect
{
public static void main(String [] args)
{
Effect e=new Effect();
e.method();
}
void method()
{
long [] a1 = {3,4,5};
long [] a2 = doArray(a1);
//expected output
System.out.println("After Calling doArray "+a1[1] +" "+ a2[1]);
String s1 = "Hello";
String s2 = doString(s1);
//expected output s1=HelloJava s2=World like earlier arrays
System.out.println("After Calling doString "+s1 + " " + s2);
}
long [] doArray(long [] a3)
{
a3[1] = 7;
System.out.println("In doArray "+ a3[0]+" "+a3[1]+" "+a3[2]);
return a3;
}
String doString(String s1)
{
s1 = s1 + "Java";
System.out.println("In doString "+ s1);
return "World";
}
}
输出
In doArray 3 7 5
After Calling doArray 7 7
In doString HelloJava
After Calling doString Hello World
我的预期输出:
After Calling doString HelloJava World
- 所有数组引用 a1,a2,a3 指向同一个。所以,修改后的数据适用于所有
- 但如果是 String,即使我们修改数据,它也会给出旧值
请解释一下?
最佳答案
在 java 中,String
对象是不可变的。
The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.
代码说明 -
String doString(String s1) {
s1 = s1 + "Java";
...
}
此处s1+"java"
将在字符串池
中创建一个新对象。并且从 method
函数引用 s1
仍将引用旧的 String
对象。
关于java - 数组和字符串充当对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22404360/