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.
Can someone help me out here? 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.
Thanks!
I had a great deal of trouble with this. I just wanted to:
Where IntervalCount is a Long, and the JSpinner was set to return a Long. Eventually I had to write this function:
which seems to do the trick. No amount of simple casting, none of the above solutions worked for me. Very frustrating.
How About
// Will not compile
// Compiles, and retains the non-NULL spirit of int. The best cast is no cast at all. Of course, your use case may require Long and possible NULL values. But if the int, or other longs are your only input, and your method can be modified, I would suggest this approach.
// Compiles, is the most efficient way, and makes it clear that the source value, is and will never be NULL.
I have this little toy, that also deals with non generic interfaces. I'm OK with it throwing a ClassCastException if feed wrong (OK and happy)
As soon as there is only method
Long.valueOf(long)
, cast fromint
tolong
will be done implicitly in case of usingLong.valueOf(intValue)
.The more clear way to do this is
If you already have the int typed as an Integer you can do this: