I have a list of strings in Java which are being written to a text file. These strings are each tagged with a type -- in this case, I'll I'm interested are strings containing long
s and int
s. I'd like to convert these strings back to a numeric type before writing them, but I'd like to minimize code duplication. I plan on parsing every string tagged as an integer or long integer using Long.parseLong()
.
My question is this: are there any situations in which a valid int开发者_开发百科eger will not parse as a long? I can't think of any (with the exception of maybe "1000L" or some such), but my experience in these matters has taught me that there are often nuances that I miss.
Yes, integers can always be cast into long, but long cant always be cast into int.
An int is really a 4-byte whole number and a long is 8 bytes. So a long gives you 4 more bytes from an int.
Long.parseLong("1000L")
results in a NumberFormatException -- it accepts string-encoded numeric values, not necessarily Java number literals (although there is a large overlap).
Because of this Long.parseLong
encompasses Integer.parseInt
entirely just as the values of int
are a proper subset of the values of long
.
Happy coding.
This should be fine, since ints are a subset of longs.
checking the description of the both methods
the answer is no (except when l or L appears after the string)
Every possible int
value can be stored in a long
or double
(or BigInteger)
精彩评论