Java 數字 默認是 Integer類型的問題,System.currentTimeMillis() + (180 * 24 * 60 * 60 * 1000)的問題,剖析、Long + Integer的問題


最終結論:

(180 * 24 * 60 * 60) 這種計算表達式在 Java中是默認以 Integer類型來的,若不超過 Integer的最大值則沒有問題,若超過則必須用 (180 * 24 * 60 * 60 * 1000L) 這種加L的方式來。

當然為了避免出現此類問題,也可以采用最粗暴的方法,就是不管 表達式的計算結果是否超過了 Integer的最大值,都用 L來標識 是個 Long類型,這樣絕對不會出錯。若是一眼就能計算出來的

可以不用加L,比如:(8 * 24 * 32) 基本肯定不會超過 Integer的最大值不用加L也行,若是一眼計算不出來感覺很大的如:(180 * 24 * 500 * 24) 這種一眼計算不出來,且感覺會超過 Integer的最大值的

需要加L來標識 計算出來的結果是一個Long類型,以防止溢出Bug.

舉例:

System.currentTimeMillis() + (24 * 60 * 60 * 1000) 這樣是不會出錯的,因為表達式的結果沒有超過 Integer,long + integer 是沒有問題的。
System.currentTimeMillis() + (180 * 24 * 60 * 60 * 1000); 這樣就會出錯,因為表達式的結果已經超過了 Integer,結果溢出了,表達式的計算結果變成了負數,導致 long - integer,最終導致計算出來的 數值 反而變小。

public class TestMain3 {
    public static void main(String[] args) {

        Long now = System.currentTimeMillis();

        System.out.println("當前時間戳:" + now);

        //當表達式的計算結果,小於 Integer的最大值時,加L與不加L都沒有問題,效果一樣
        System.out.println("180 * 24 * 60 * 60: " + (180 * 24 * 60 * 60));
        System.out.println("180 * 24 * 60 * 60L: " + (180 * 24 * 60 * 60L));
        System.out.println(now + (180 * 24 * 60 * 60));
        System.out.println(now + (180 * 24 * 60 * 60L));

        //當表達式的計算結果,大於 Integer的最大值時,由於 溢出了會變成負數,所以最終的結果反而會變小
        System.out.println("180 * 24 * 60 * 60 * 1000: " + (180 * 24 * 60 * 60 * 1000));
        System.out.println("180 * 24 * 60 * 60 * 1000L: " + (180 * 24 * 60 * 60 * 1000L));
        System.out.println(now + (180 * 24 * 60 * 60 * 1000) + "(這里變小了,引起Bug)");
        System.out.println(now + (180 * 24 * 60 * 60 * 1000L));



    }
}

 

 

==================================================================================================================================================

 

今天黃克說我生成的Token老是會過期,我郁悶,檢查了一下代碼 發現:

 

 

心想難道 (180 * 24 * 60 * 60 * 1000)這一串默認是 Integer類型,接下來開始測試:

 

 

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM