1. Introduction
1.导言
Data type conversions form a critical part of programming in any language. In Java, developers frequently need to convert an int to a Long or vice-versa, as presented in our article.
数据类型转换是任何语言编程的关键部分。在 Java 中,开发人员经常需要将 int 转换为 Long 或反之,如我们的 文章所述。
While this operation may seem straightforward, Java offers several methods with unique characteristics and use cases.
虽然这种操作看似简单,但 Java 提供了几种具有独特特征和用例的方法。
In this tutorial, we’ll delve into these methods, providing a clear understanding of how each approach works and when to use them.
在本教程中,我们将深入探讨这些方法,清楚地了解每种方法的工作原理和使用时机。
2. The Basics: Understanding int and Long
2.基础知识:了解 int 和 Long
Before we explore the conversion methods, let’s first understand what int and Long are. Both int and Long are different types of data types we use in Java to store numerical values.
在探索转换方法之前,让我们先了解一下什么是 int 和 Long 。int 和 Long 都是 Java 中用于存储数值的不同数据类型。
The int data type is a 32-bit signed two’s complement integer, which can hold a minimum value of -2^31 and a maximum value of 2^31-1.
int 数据类型是 32 位有符号二进制整数,最小值为 -2^31,最大值为 2^31-1。
In contrast, Long is a 64-bit two’s complement integer, which can hold values from -2^63 to 2^63-1. We usually use Long when the range provided by int is not sufficient.
相比之下,Long 是一个 64 位二进制整数,可容纳 -2^63 到 2^63-1 的值。当 int 提供的范围不够大时,我们通常会使用 Long 。
3. Autoboxing: the Implicit Conversion
3.自动装箱:隐性转换
Java introduced a feature called autoboxing in its 5th version, which allows automatic conversion between primitive types and their corresponding wrapper classes.
Java 在第 5 版中引入了一项名为自动装箱的功能,它允许在基元类型和相应的封装类之间进行自动转换。
Let’s use autoboxing to convert an int to a Long directly:
让我们使用自动开箱功能将 int 直接转换为 Long :
int intTen = 10;
Long longTen = (long) intTen;
We declare an int variable intTen and assign it a value of 10. We then declare a Long variable longTen, and assign it the value of intTen. The (long) before intTen is a type-casting operator that tells the compiler to convert intTen to long before assigning it to longTen. This process is automatic, hence the term autoboxing.
我们声明一个 int 变量 intTen,并将其赋值为 10。然后,我们声明一个 Long 变量 longTen,并赋予它 intTen 的值。intTen 前面的 (long) 是一个类型转换操作符,它告诉编译器在将 intTen 赋值给 longTen 之前,先将 intTen 转换为 long 。这一过程是自动进行的,因此称为 autoboxing。
4. Using Long.valueOf(): the Wrapper Class Method
4.使用 Long.valueOf():封装类方法
The Long class in Java is a wrapper class that provides several utility methods for dealing with long values. One such method is valueOf(), which can take an int and return a Long object.
Java 中的 Long 类是一个封装类,它提供了多个用于处理 long 值的实用方法。其中一个方法是 valueOf(),它可以接收一个 int 并返回一个 Long 对象。
This method is a straightforward and efficient way to convert an int to a Long:
该方法是将 int 转换为 Long 的一种直接而有效的方法:
int intTen = 10;
Long longTen = Long.valueOf(intTen);
We use the valueOf() method of the Long class to convert the int value to a Long. The valueOf() method returns a Long instance representing the specified int value. This method is part of the Long class, which is a wrapper class for the long data type in Java.
我们使用 Long 类的 valueOf() 方法将 int 值转换为 Long 值。valueOf() 方法返回一个 Long 实例,代表指定的 int 值。该方法是 Long 类的一部分,该类是 Java 中 long 数据类型的封装类。
5. Using new Long() Constructor: the Object Creation Method
5.使用 new Long() 构造函数:对象创建方法
Another way to convert an int to a Long is by using the Long constructor. This method creates a new Long object from an int. However, this approach is less efficient due to the overhead of creating a new object:
将 int 转换为 Long 的另一种方法是使用 Long 构造函数。该方法可从 int 创建一个新的 Long 对象。但是,由于创建新对象的开销较大,这种方法的效率较低:
int intTen = 10;
Long longTen = new Long(intTen);
We create a new Long object by using the Long constructor. The Long constructor takes an int value and creates a new Long object representing the same numerical value. While this method is straightforward, we should avoid using it for performance-critical applications due to object creation overhead, so the static factory valueOf() is generally a better choice.
我们使用 Long 构造函数创建一个新的 Long 对象。Long 构造函数接收一个 int 值,并创建一个代表相同数值的新 Long 对象。虽然该方法简单明了,但由于创建对象的开销较大,我们应避免将其用于对性能要求较高的应用程序,因此静态工厂 valueOf() 通常是更好的选择。
6. Using Long.parseLong(): the String Conversion Method
6.使用 Long.parseLong():字符串转换方法
We typically use the Long.parseLong() method to convert a String to a Long. However, we can also use it with an int by first converting the int to a String:
我们通常使用 Long.parseLong() 方法将 String 转换为 Long 。不过,我们也可以将其用于 int 中,首先将 int 转换为 String :
int intTen = 10;
Long longTen = Long.parseLong(String.valueOf(intTen));
We first convert the int to a String using the String.valueOf() method. We then pass this String to the Long.parseLong() method, which parses the String as a long value and returns a Long object representing this value. This method is a bit roundabout, but it can be helpful in specific scenarios where the input is a String.
我们首先使用 String.valueOf() 方法将 int 转换为 String 。然后,我们将此 String 传递给 Long.parseLong() 方法,该方法将 String 解析为 long 值,并返回代表此值的 Long 对象。该方法有点迂回,但在输入为 String 的特定应用场景中很有帮助。
7. Additional Considerations
7.其他考虑因素
When converting from int to Long, it’s important to note that you’re going from a smaller data type to a larger one. This means there’s no risk of losing data during the conversion.
在从 int 转换为 Long 时,重要的是要注意从较小的数据类型转换为较大的数据类型。这意味着在转换过程中不会有丢失数据的风险。
However, the reverse operation (from Long to int) may result in data loss if the Long value is larger than Integer.MAX_VALUE, which represents the maximum positive integer value that can be represented in 32 bits, holds the result of the formula 2^31-1 (i.e. 2147483647).
但是,如果 Long 值大于 Integer.MAX_VALUE,则反向操作(从 Long 到 INT)可能会导致数据丢失。Integer.MAX_VALUE 代表可用 32 位表示的最大正整数值,持有公式 2^31-1 的结果(即 2147483647)。
Also, while the Long data type can hold larger values, it consumes more memory. An int in Java takes up 4 bytes of memory, while a Long takes up 8 bytes. Therefore, it’s important to consider the memory implications when deciding to use Long instead of int.
此外,虽然 Long 数据类型可以保存更大的值,但它消耗的内存也更多。在 Java 中,一个 int 会占用 4 字节内存,而一个 Long 会占用 8 字节内存。因此,在决定使用 Long 而不是 int 时,必须考虑内存影响。
8. Deep Dive: Understanding the Underlying Mechanisms
8.深入研究:了解基本机制
To fully appreciate the conversion methods, it’s beneficial to understand the underlying mechanisms. Autoboxing, for instance, is a syntactic sugar that the Java compiler provides. It automatically inserts the necessary code to convert between the primitive type and the corresponding wrapper class. This feature simplifies the code and makes it more readable.
要充分了解转换方法,最好先了解其基本机制。例如,自动装箱是 Java 编译器提供的一种语法糖。它会自动插入必要的代码,在基元类型和相应的封装类之间进行转换。这一功能简化了代码,使其更具可读性。
On the other hand, the valueOf() method and the Long constructor are part of the Long class, a wrapper class for the long primitive type. Wrapper classes in Java provide a way to use primitive data types as objects. They offer several utility methods, including those for conversion, which we use in our examples.
另一方面,valueOf() 方法和 Long 构造函数是 Long 类的一部分,该类是 long 原始类型的封装类。Java 中的封装类提供了一种将基元数据类型用作对象的方法。它们提供了多种实用方法,包括我们在示例中使用的转换方法。
Notably, the valueOf() method is favored for its object reusability through internal caching for values ranging from -128 to 127, improved performance, minimized garbage collection, code consistency, alignment with autoboxing, and sustained applicability, especially considering the deprecation of the new Long() constructor in recent Java versions.
值得注意的是,valueOf() 方法通过内部缓存实现了从 -128 到 127 的值的对象重用性,提高了性能,最大限度地减少了垃圾回收,实现了代码一致性,与自动排序保持一致,并具有持续适用性,特别是考虑到在最近的 Java 版本中,新的 Long() 构造函数已被淘汰。
The parseLong() method, typically used for String to Long conversion, can also handle int to Long conversion. However, it requires an extra step of first converting the int to a String. This method is a bit more roundabout, but it’s useful when dealing with numerical inputs that come in string format, such as user inputs or data read from a file.
parseLong() 方法通常用于 String 到 Long 的转换,它也可以处理 int 到 Long 的转换。不过,它需要额外的步骤,即首先将 int 转换为 字符串。这种方法比较迂回,但在处理字符串格式的数字输入(如用户输入或从文件中读取的数据)时非常有用。
9. Conclusion
9.结论
We can convert an int to a Long in Java in several ways, each method has advantages and use cases. Autoboxing is a simple and direct approach, while Long.valueOf() and Long.parseLong() provide more explicit conversions. The Long constructor can also be used, but it’s less efficient due to the object creation overhead.
在 Java 中,我们可以通过几种方法将 int 转换为 Long,每种方法都有各自的优势和用例。Autoboxing 是一种简单直接的方法,而 Long.valueOf() 和 Long.parseLong() 则提供了更明确的转换。也可以使用 Long 构造函数,但由于需要创建对象,因此效率较低。
Choosing the method that best fits your needs and the context of your code is essential.
选择最适合您的需求和代码上下文的方法至关重要。
As always, the complete code samples for this article can be found over on GitHub.
与往常一样,本文的完整代码示例可在 GitHub 上找到。