[英]Can an integer always be parsed as a long?
I have a list of strings in Java which are being written to a text file. 我有一个Java中的字符串列表,正在写入文本文件。 These strings are each tagged with a type -- in this case, I'll I'm interested are strings containing
long
s and int
s. 这些字符串都标有一个类型 - 在这种情况下,我感兴趣的是包含
long
s和int
的字符串。 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()
. 我计划使用
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.
我想不出任何东西(除了可能是“1000L”或其他一些),但我在这些事情上的经验告诉我,我经常会有细微差别。
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. int实际上是一个4字节的整数,long是8字节。 So a long gives you 4 more bytes from an int.
所以long给你一个int多4个字节。
Long.parseLong("1000L")
results in a NumberFormatException -- it accepts string-encoded numeric values, not necessarily Java number literals (although there is a large overlap). Long.parseLong("1000L")
导致NumberFormatException - 它接受字符串编码的数值,不一定是Java数字文字(尽管有很大的重叠)。
Because of this Long.parseLong
encompasses Integer.parseInt
entirely just as the values of int
are a proper subset of the values of long
. 因为
Long.parseLong
完全包含Integer.parseInt
,因为int
的值是long
值的正确子集。
Happy coding. 快乐的编码。
这应该没问题,因为整数是多头的子集。
每个可能的int
值都可以存储在long
或double
(或BigInteger)中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.