简体   繁体   English

Java。 争论没有改变

[英]Java. Argument does not change

static void f(String s)
{
    s = "x";
}

public static void main(String[] args) {
  String s = null;
  f(s);
}

Why the value of s after calling f(s) is null instead of "x"? 为什么调用f(s)后s的值为null而不是“ x”?

Because s is a reference. 因为s是参考。 You pass a copy of that reference to the method, and then modify that copy inside the method. 您将该引用的副本传递给该方法,然后在该方法内部修改该副本。 The original doesn't change. 原件不变。

When passing an Object variable to a function in java, it is passed by reference. 将Object变量传递给Java中的函数时,它通过引用传递。 If you assign a new value to the object in the function, then you overwrite the passed in reference without modifying the value seen by any calling code which still holds the original reference. 如果在函数中为对象分配新值,则将覆盖传入的引用,而不会修改任何仍保留原始引用的调用代码看到的值。

However, if you do the following then the value will be updated: 但是,如果执行以下操作,则值将被更新:

public class StringRef
{
  public String someString;
}

static void f(StringRef s)
{
  s.someString = "x";
}

public static void main(String[] args)
{
  StringRef ref = new StringRef;
  ref.someString = s;
  f(ref);
  // someString will be "x" here.
}

Within the function f() the value will be "x". 在函数f()中,该值为“ x”。 Outside of this function the value of s will be null. 在此函数之外,s的值为null。 Reference data types (such as objects) are passed by value see here (read the section "Passing Reference Data Type Arguments") 参考数据类型(例如对象)通过值传递,请参见此处 (请阅读“传递参考数据类型参数”一节)

Given that s is of type String , which is a reference type (not a primitive): 假设sString类型,这是引用类型(不是原始类型):

s = "x";

does not mean "transform the thing that s refers to into the value "x" ". 并不意味着“变换的东西s是指到值"x" ”。 (In a language where null is a possibility, it can't really do that anyway, because there is no actual "thing that s refers to" to transform.) (在可能存在null的语言中,它无论如何都不能真正做到这一点,因为没有实际的“ s所指事物”来进行转换。)

It actually means "cause s to stop referring to the thing it currently refers to, and start referring to the value "x" ". 实际上,它的意思是“使s停止引用其当前引用的事物,而开始引用值"x" ”。

The name s in f() is local to f() , so once the function returns, that name is irrelevant; 该名sf()是本地的f()所以一旦函数返回时,该名称是无关紧要的; the name s in main() is a different name, and is still a null reference. main()的名称s是一个不同的名称,并且仍然是null引用。

The only thing that the parameter passing accomplishes is to cause s in f() to start out as null . 传递的参数唯一要做的就是使f() snull开始。

This explanation would actually go somewhat more smoothly if you hadn't used null :( 如果您没有使用null :(

Actually you are not changing the value you are creating new one, it is totally different, If you change an attribute of the abject in the method then i will be changed in your references. 实际上,您并没有更改要创建的值,而是完全不同的。如果您在方法中更改对象的属性,那么我的引用将被更改。 But you are creating new object. 但是您正在创建新对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM