0

I am quite confused with how Object works in Java since I run into this problem.

Let's say I have a function called checkDateValue (code looks like this)

private boolean checkDateValue(Date d1, String msg) {
    if (d1 == null) {
        msg = "d1 is null!";
        return false;
    }
    return true;
}

Here is the place I call this function:

String msg = null;
Date d1 = null;
if (!checkDateValue(d1, msg)) {
    system.println(msg); //msg is still null..... 
                         //what I need is the message generated in the function
}

As far as I know, if I put a customized Object (e.g.

myObj { private String msg;} 

) into a function, and we change the value of msg inside the function, when we get out of the function, the change of msg is kept. However, I think String is also considered as an Object in java. Why the change is not kept?

4

6 回答 6

2

Java 没有"out"函数参数;它们是参考文献的副本。即使您更改msg了函数,它也不会影响调用者的变量。

于 2013-04-30T18:49:51.357 回答
1

String 是特殊的,是不可变的,与普通的 Object 不同。Java 的String被设计为介于原语和类之间。

String是按值传递的,但不幸的是,String 上的每次更改都会产生新值,因此您的旧引用具有旧值。

我认为这是很好的解释:https ://stackoverflow.com/a/1270782/516167

于 2013-04-30T18:49:14.713 回答
0

在 Java 中,您不能通过分配给方法参数来将值传回给调用代码。您是对的,您可以更改任何参数的内部结构,并且该更改将在调用代码中看到。但是,分配给参数与更改内部结构不同。此外,aString不可变的——一旦创建,它的内部结构就不能改变。

一个常见的技巧来做你什么是使用数组参数:

private boolean checkDateValue(Date d1, String[] msg) {
    if (d1 == null) {
        msg[0] = "d1 is null!";
        return false;
    }
    return true;
}

然后像这样调用它:

String[] msg = new String[1];
Date d1 = null;
if (!checkDateValue(d1, msg)) {
    system.println(msg[0]);
}
于 2013-04-30T18:49:17.373 回答
0

msg = "d1 is null!";并且msg=null是两个不同的 String 对象。String在 Java 中是不可变的。引用是按值传递的,即传递引用的副本。并且由于 aString是不可变对象,因此方法内部的赋值创建了一个新String对象,引用的副本现在指向该对象。原始引用仍然指向 null String。您的方法调用与以下内容相同:

Object obj = null; // obj points to nowhere
foo(obj); // passed the reference values to method argument
void foo(Object o)
{
   o = new Object( );  // o points to new Object, but obj still points to nowhere
}
于 2013-04-30T18:46:41.433 回答
0

这与以下事实有关

Java 将对象作为按值传递的引用传递。

不能将引用参数更改为指向其他内容。您可以更改对象状态。

你可以在这里阅读更多

于 2013-04-30T18:51:05.737 回答
0
if (!checkDateValue(d1, msg)) 

{
    system.println(msg); 
} 

当您调用checkDateValue方法时,会传递对方法的引用String msg = null; Date d1 = null;,该方法是按值传递的。当方法被执行时, msg变量 incheckDateValue将被引用到“d1 is null!” 在这里,msg调用中的变量保持不变

于 2017-02-21T10:35:10.993 回答