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 integer 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.
这应该没问题,因为整数是多头的子集。
每个可能的int
值都可以存储在long
或double
(或BigInteger)中
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.