Java 中函數參數傳遞和函數返回值都是以值方式傳遞的。當然,對于對象,我們也可以說是引用的方式傳遞,其實傳遞也是值,只不過是引用值。引用是一個對象的別名,對于引用的修改就是對于對象本身的修改。
為了便于理解還是可以說成是兩種類型,原始類型以值方式傳遞,對象以引用方式傳遞。
向函數里傳遞參數,已經有很多java教程講解了。這里主要記錄一個 函數返回值的問題。在返回一個對象時,是返回值本身的應用,還是拷貝這個值,再傳拷貝的引用呢。這是需要考慮清楚的。
這個問題,是我在 不同手機上調試 J2ME 程序時遇到的。
具體如下,這是一個關于時間的工具類。我發覺 Calendar 的 getTime() 在有的機器下 如 Nokia,返回的 Calendar 當前時間的一個拷貝的引用,而 SAMSUNG 則直接返回 Calendar 的當前時間的引用。這導致,我在想得到一個時間所在那一的起始時間和結束時間時,總是得到相同的值,即后一次調用的值。按照,比較正常的理解,這里應該返回拷貝的引用比較正確,就是說 SAMSUNG 的 JVM 實現有些問題。面對這種情況,我只能先用 Date 類 返回 一個 long 值,再用 long 值構造一個新日期,即日歷當前日期的拷貝,返回這個拷貝。
修改函數中的最后一行為
return new Date(fCalendar.getTime().getTime());
private static Date fCalendar = Calendar.getInstance();
/**
* Get the beginning of a day
* @param date <description>
* @return <description>
*/
public static Date getBeginOfDay( final Date pDate ) {
fCalendar.setTime( pDate );
try{
fCalendar.set( Calendar.HOUR_OF_DAY, 0 );
fCalendar.set( Calendar.MINUTE, 0 );
fCalendar.set( Calendar.SECOND, 0 );
}catch(ArrayIndexOutOfBoundsException ex){
ex.printStackTrace();
}
return fCalendar.getTime();
}
/**
* Get the end of a day
* @param date <description>
* @return <description>
*/
public static Date getEndOfDay( final Date pDate ){
fCalendar.setTime( pDate );
try{
fCalendar.set( Calendar.HOUR_OF_DAY, 23 );
fCalendar.set( Calendar.MINUTE, 59 );
fCalendar.set( Calendar.SECOND, 59 );
}catch(ArrayIndexOutOfBoundsException ex){
ex.printStackTrace();
}
return fCalendar.getTime();
}
/**
* Get the beginning of a day
* @param date <description>
* @return <description>
*/
public static Date getBeginOfDay( final Date pDate ) {
fCalendar.setTime( pDate );
try{
fCalendar.set( Calendar.HOUR_OF_DAY, 0 );
fCalendar.set( Calendar.MINUTE, 0 );
fCalendar.set( Calendar.SECOND, 0 );
}catch(ArrayIndexOutOfBoundsException ex){
ex.printStackTrace();
}
return fCalendar.getTime();
}
/**
* Get the end of a day
* @param date <description>
* @return <description>
*/
public static Date getEndOfDay( final Date pDate ){
fCalendar.setTime( pDate );
try{
fCalendar.set( Calendar.HOUR_OF_DAY, 23 );
fCalendar.set( Calendar.MINUTE, 59 );
fCalendar.set( Calendar.SECOND, 59 );
}catch(ArrayIndexOutOfBoundsException ex){
ex.printStackTrace();
}
return fCalendar.getTime();
}