更新 java.sql.Timestamp
Update java.sql.Timestamp
我想用其他方法更新 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;
}
}
}
Java 使用 CallByValue
。这意味着值被传输到方法而不是对对象的引用。所以 a will 只会在你的函数内部改变。
如果您想在 `main 函数中更改它,您必须通过 return 值取回它。
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;
}
}
我想用其他方法更新 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;
}
}
}
Java 使用 CallByValue
。这意味着值被传输到方法而不是对对象的引用。所以 a will 只会在你的函数内部改变。
如果您想在 `main 函数中更改它,您必须通过 return 值取回它。
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;
}
}