我想在其他方法中更新java.sql.Timestamp
。但它没有在main
方法中更新。为什么?这是通过值还是参考传递的?
package test;
import java.sql.Timestamp;
import java.util.Date;
public class Test {
public static void main(String[] args) throws InterruptedException {
Timestamp a = null;
Date now = new Date();
Timestamp b = new Timestamp(now.getTime());
update(a, b);
System.out.println(a); // returns "null", why?
}
/**
* Sets the newer timestamp to the old if it is possible.
* @param a an old timestamp
* @param b a new timestamp
*/
private static void update(Timestamp a, Timestamp b) {
if(b == null) {
//nothing
} else if(a == null) {
a = b;
} else if(a.after(b)) {
a = b;
}
}
}
答案 0 :(得分:2)
Java使用CallByValue
。这意味着该值被转移到方法而不是对象的引用。所以只会改变你的内心。
如果您想在`main函数中更改它,您必须通过返回值将其恢复。
package test;
import java.sql.Timestamp;
import java.util.Date;
public class Test {
public static void main(String[] args) throws InterruptedException {
Timestamp a = null;
Date now = new Date();
Timestamp b = new Timestamp(now.getTime());
a = update(a, b);
System.out.println(a); // returns "null", why?
}
/**
* Sets the newer timestamp to the old if it is possible.
* @param a an old timestamp
* @param b a new timestamp
*/
private static Timestamp update(Timestamp a, Timestamp b) {
if(b == null) {
//nothing
} else if(a == null) {
a = b;
} else if(a.after(b)) {
a = b;
}
return a;
}
}