Java 关于向方法传递值的混淆?
我真的很困惑如何将值传递给函数。我无法确定当我们将值传递给函数时,哪些类型的值会发生更改 示例1-将字符串(引用类型)传递给函数-Java 关于向方法传递值的混淆?,java,pass-by-reference,pass-by-value,Java,Pass By Reference,Pass By Value,我真的很困惑如何将值传递给函数。我无法确定当我们将值传递给函数时,哪些类型的值会发生更改 示例1-将字符串(引用类型)传递给函数- public static String word = new String("Hello World"); public static void main(String[] args) { System.out.println("Before: " + word); UpdateValue(word);
public static String word = new String("Hello World");
public static void main(String[] args)
{
System.out.println("Before: " + word);
UpdateValue(word);
System.out.println("After: " + word);
}
public static void UpdateValue(String x)
{
x = "Hi World";
}
public static String[] words = new String[] {"Hello", "Everyone"};
public static void main(String[] args)
{
System.out.println("Before: " + Arrays.toString(words));
UpdateValue(words);
System.out.println("After: " + Arrays.toString(words));
}
public static void UpdateValue(String[] x)
{
x[0] = "Hi";
}
输出:
之前:你好,世界
之后:你好,世界
示例2-将字符串[]数组传递给函数-
public static String word = new String("Hello World");
public static void main(String[] args)
{
System.out.println("Before: " + word);
UpdateValue(word);
System.out.println("After: " + word);
}
public static void UpdateValue(String x)
{
x = "Hi World";
}
public static String[] words = new String[] {"Hello", "Everyone"};
public static void main(String[] args)
{
System.out.println("Before: " + Arrays.toString(words));
UpdateValue(words);
System.out.println("After: " + Arrays.toString(words));
}
public static void UpdateValue(String[] x)
{
x[0] = "Hi";
}
输出:
Before:[大家好]
之后:[大家好]
我的问题-
public static String word = new String("Hello World");
public static void main(String[] args)
{
System.out.println("Before: " + word);
UpdateValue(word);
System.out.println("After: " + word);
}
public static void UpdateValue(String x)
{
x = "Hi World";
}
public static String[] words = new String[] {"Hello", "Everyone"};
public static void main(String[] args)
{
System.out.println("Before: " + Arrays.toString(words));
UpdateValue(words);
System.out.println("After: " + Arrays.toString(words));
}
public static void UpdateValue(String[] x)
{
x[0] = "Hi";
}
- 这一切是如何运作的
是一种引用类型,因此我的 先前的假设是,如果我们传递它,值将发生变化 对一个函数进行修改。但那没有发生。值没有改变String
- 同时,当我传递数组(在Java中是一个对象,所以基本上是一个引用)时 类型?)我们看到原始的值已更改
我是第二个例子,对数组的引用也是以同样的方式复制的。本地引用指向与main中相同的数组。但是这次数组引用没有更新。相反,数组中的一个字符串引用被更新为指向一个新的字符串对象。在Java中,对象是按值传递的,但值是对对象的引用(数组也是对象),在示例1中,您将另一个对象的引用分配给参数,因此如果它是按值传递的,则不会更新调用方。在示例2中,您正在更新数组内的引用,因此调用方可以看到更改,因为它与传入的数组相同。顺便说一句:使用
新字符串(“helloworld”)
是不必要和浪费的,被认为是一种不好的做法。