問題描述
我一直在這里和谷歌上發現從 long
到 int
而不是相反的問題.但我確信在從 int
到 Long
之前遇到這種情況的人不止我一個.
I keep finding both on here and Google people having troubles going from long
to int
and not the other way around. Yet I'm sure I'm not the only one that has run into this scenario before going from int
to Long
.
我發現的唯一其他答案是首先將其設置為 Long",這確實沒有解決問題.
The only other answers I've found were "Just set it as Long in the first place" which really doesn't address the question.
我最初嘗試強制轉換,但得到Cannot cast from int to Long
"
I initially tried casting but I get a "Cannot cast from int to Long
"
for (int i = 0; i < myArrayList.size(); ++i ) {
content = new Content();
content.setDescription(myArrayList.get(i));
content.setSequence((Long) i);
session.save(content);
}
你可以想象我有點困惑,我被困在使用 int
因為一些內容是作為一個 ArrayList
和我的實體進入的m 存儲此信息需要序列號為 Long.
As you can imagine I'm a little perplexed, I'm stuck using int
since some content is coming in as an ArrayList
and the entity for which I'm storing this info requires the sequence number as a Long.
推薦答案
請注意,轉換為 long
和轉換為 Long
之間存在差異.如果你轉換成 long
(一個原始值),那么它應該被自動裝箱成一個 Long
(包裝它的引用類型).
Note that there is a difference between a cast to long
and a cast to Long
. If you cast to long
(a primitive value) then it should be automatically boxed to a Long
(the reference type that wraps it).
您也可以使用 new
創建 Long
的實例,并使用 int
值對其進行初始化.
You could alternatively use new
to create an instance of Long
, initializing it with the int
value.
這篇關于如何在 Java 中將 int 轉換為 Long?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!