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
.
The only other answers I've found were "Just set it as Long in the first place" which really doesn't address the question.
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); }
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.
To initialize long you need to append "L" to the end. It can be either uppercase or lowercase. All the numeric values are by default int . Even when you do any operation of byte with any integer, byte is first promoted to int and then any operations are performed.
There are many methods for converting a String to a Long data type in Java which are as follows: Using the parseLong() method of the Long class. Using valueOf() method of long class. Using constructor of Long class.
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).
You could alternatively use new
to create an instance of Long
, initializing it with the int
value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With