2015-02-11 71 views
0

我想用其他方法更新java.sql.Timestamp。但在main方法中沒有更新。爲什麼?這是通過價值或參考傳遞?更新java.sql.Timestamp

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

可能是[是Java「pass-by-reference」還是「pass-by-value」?)重複(http://stackoverflow.com/questions/40480/is-java-pass-by-基準或通按值) – Jonathan 2015-02-11 08:50:49

回答

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; 
    } 
} 
相關問題