關(guān)于Long和Integer相互轉(zhuǎn)換方式
一、int和long互相轉(zhuǎn)換
(一)long轉(zhuǎn)化為int
(1)類型強制轉(zhuǎn)換
long numberLong = 123L;// "L"理論上不分大小寫,但是若寫成"l"容易與數(shù)字"1"混淆,不容易分辯。所以最好大寫。 int numberInt = (int) numberLong;
注意:
int有4個字節(jié),取值范圍為[-231,231 - 1]
long有8個字節(jié),[-263 ,263 -1]
如果long的值超過了int區(qū)值范圍,會出現(xiàn)值溢出的問題:

就會得以下內(nèi)容:

這是因為:當取值范圍超過int的最大值時,會變?yōu)閕nt取值范圍的最小值,不會繼續(xù)增長了。

(2)利用BigDecimal強制轉(zhuǎn)換
long numberLong = 100L; BigDecimal numBigDecimal = new BigDecimal(numberLong); // 或 numBigDecimal = BigDecimal.valueOf(numberLong); int numberInt = numBigDecimal.intValue();
(二)int轉(zhuǎn)化為long
(1)類型強制轉(zhuǎn)換
long numberLong = 123L;// "L"理論上不分大小寫,但是若寫成"l"容易與數(shù)字"1"混淆,不容易分辯。所以最好大寫。 int numberInt = (int) numberLong;
(2)利用BigDecimal強制轉(zhuǎn)換
int numberInt = 100; BigDecimal bigNumber = new BigDecimal(numberInt); // 或者 BigDecimal bigNumber = BigDecimal.valueOf(numberInt); long numberLong = bigNumber.longValue();
二、Long和Integer的互相轉(zhuǎn)換
(一)Long轉(zhuǎn)化為Integer
(1)類型強制轉(zhuǎn)化(不可用)

會出現(xiàn)報錯

報編譯錯: 無法轉(zhuǎn)換的類型,Long不能被強制轉(zhuǎn)化為Integer。
(2)使用Long的api
Long numberLong = new Long(1000L); Integer intNumber = numberLong.intValue();
(3)利用String轉(zhuǎn)換
Long longValue = new Long(1000l); String strValue = longValue.toString(); // 或者 Integer intValue = new Integer(strValue); Integer intValue = Integer.valueOf(strValue);
(二)Integer轉(zhuǎn)化為Long
(1)類型強制轉(zhuǎn)化(不可用)

(2)使用Integer的api
Integer intValue = new Integer(1000); Long longValue = intValue.longValue();
(3)使用Long的構(gòu)造方法
Integer intValue = new Integer(1000); Long longValue = new Long(intValue);
(4)利用String
Integer intValue = new Integer(1000); String strValue = intValue.toString(); Long longValue = new Long(strValue);
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
淺談synchronized加鎖this和class的區(qū)別
synchronized 是 Java 語言中處理并發(fā)問題的一種常用手段,本文主要介紹了synchronized加鎖this和class的區(qū)別,具有一定的參考價值,感興趣的可以了解一下2021-11-11
SpringBoot使用mybatis-plus分頁查詢無效的問題解決
MyBatis-Plus提供了很多便捷的功能,包括分頁查詢,本文主要介紹了SpringBoot使用mybatis-plus分頁查詢無效的問題解決,具有一定的參考價值,感興趣的可以了解一下2023-12-12
Java網(wǎng)絡(luò)編程之IO模型阻塞與非阻塞簡要分析
這篇文章主要介紹Java網(wǎng)絡(luò)編程中的IO模型阻塞與非阻塞簡要分析,文中附有示例代碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-09-09

