在 Java 中将 int(primitive) 转换为 Long(wrapper) 的最佳方法

Best way to cast int(primitive) to Long(wrapper) in Java

我在 Java 中有一个原始类型 int "pubNumber"。

我想将其转换为 "Long"(非原始),据我了解,有以下方法可以做到这一点。

1. Long.valueOf(pubNumber)
2. (long) pubNumber
3. new Long(pubNumber)

谁能帮我看看哪一个是最好的方法,为什么?

Long.valueOf(pubNumber) 是最好的方法,因为它使用缓存中的值(如果存在)。

阅读here

public static Long valueOf(long l)
Returns a Long instance representing the specified long value. If a new Long instance is not required, this method should generally be used in preference to the constructor Long(long), as this method is likely to yield significantly better space and time performance by caching frequently requested values. Note that unlike the corresponding method in the Integer class, this method is not required to cache values within a particular range.

Parameters: l - a long value.
Returns: a Long instance representing l.
Since: 1.5

你应该避免 new Long(pubNumber),因为那个总是会创建一个新的 Long 实例。

另一方面,如果要转换为 Long 的值在 -128 到 127 之间,Long.valueOf(pubNumber) 将 return 一个缓存的 Long 实例。

(long) pubNumber 的行为应该与 Long.valueOf(pubNumber) 相同,因为在转换为 long 之后,它将自动装箱为 Long,我相信自动- longLong 的装箱使用 Long.valueOf().

Long.valueOf(pubNumber) 和 new Long 的区别在于,使用 new Long() 总是会创建一个新对象,而使用 Long.valueOf() 时,可能 return如果值在 [-128 到 127] 之间,则您是 long 的缓存值。

所以,你应该更喜欢Long.valueOf方法,因为它可以节省你一些内存。