Convert long to int Type in Java – 在Java中把长字符串转换为int类型

最后修改: 2022年 3月 14日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll see how we can convert a long value to an int type in Java. Before we start coding, we need to point out some details about this data type.

在本教程中,我们将看到如何在Java中把一个long值转换成int类型。在我们开始编码之前,我们需要指出关于这种数据类型的一些细节。

First of all, in Java, long values are represented by signed 64-bit numbers. On the other hand, int values are represented by signed 32-bit numbers. Therefore, converting a higher data type into a lower one is called narrowing type casting. As a result of these conversions, some bits would be lost when long values are larger than Integer.MAX_VALUE and Integer.MIN_VALUE.

首先,在Java中,long值是由有符号的64位数表示。另一方面,int值由有符号的32位数表示。因此,将较高的数据类型转换为较低的数据类型被称为缩小类型铸造。由于这些转换,当long值大于Integer.MAX_VALUEInteger.MIN_VALUE时,一些位会被丢失。

Additionally, we’ll show for each conversion variant, how it works for a long value equals to Integer.MAX_VALUE plus one.

此外,我们将展示每个转换变量,对于一个值等于Integer.MAX_VALUE加1的情况,它是如何工作的。

2. Data Conversion

2.数据转换

2.1. Casting Values

2.1.铸造价值

First, casting values in Java is the most common way of type conversion – it’s straightforward:

首先,Java中的铸值是最常见的类型转换方式–它很直接。

public int longToIntCast(long number) {
    return (int) number;
}

2.2. Java 8

2.2.Java 8

Since Java 8, we can use two more ways to do type conversion: using the Math package or using a lambda function. For the Math package, we can use the toIntExact method:

从Java 8开始,我们又可以使用两种方式来进行类型转换:使用Math包或使用lambda函数。对于Math包,我们可以使用toIntExactmethod。

public int longToIntJavaWithMath(long number) {
return Math.toIntExact(number);
}

2.3. Wrapper Class

2.3.封装器类

On the other hand, we can use the wrapper class Long to get the int value:

另一方面,我们可以使用包装类Long来获取int值。

public int longToIntBoxingValues(long number) {
    return Long.valueOf(number).intValue();
}

2.4. Using BigDecimal

2.4.使用BigDecimal

Moreover, we can accomplish this conversion using the BigDecimal class:

此外,我们可以使用BigDecimal类完成这种转换。

public static int longToIntWithBigDecimal(long number) {
    return new BigDecimal(number).intValueExact();
}

2.5. Using Guava

2.5.使用Guava

Next, we’ll show type conversion using Google Guava‘s Ints class:

接下来,我们将使用Google GuavaInts类展示类型转换。

public int longToIntGuava(long number) {
    return Ints.checkedCast(number);
}

In addition, Google Guava‘s Ints class provides a saturatedCast method:

此外,Google GuavaInts类提供了一个saturatedCast方法。

public int longToIntGuavaSaturated(long number) {
    return Ints.saturatedCast(number);
}

2.6. Integer Upper and Under Bounds

2.6.整数的上界和下界

Finally, we need to consider that an integer value has an upper and under bound. These limits are defined by Integer.MAX_VALUE and Integer.MIN_VALUE. For values out of those limits, results are different from one method to another.

最后,我们需要考虑,一个整数值有一个上界和下界。这些限制是由Integer.MAX_VALUEInteger.MIN_VALUE定义。对于超出这些限制的值,不同方法的结果是不同的。

In the next code snippet, we’ll test the case when an int value is unable to hold the long value:

在下一个代码片段中,我们将测试当int值无法容纳long值的情况。

@Test
public void longToIntSafeCast() {
    long max = Integer.MAX_VALUE + 10L;
    int expected = -2147483639;
    assertEquals(expected, longToIntCast(max));
    assertEquals(expected, longToIntJavaWithLambda(max));
    assertEquals(expected, longToIntBoxingValues(max));
}

Using direct cast, with lambda or using boxing values produces a negative value. In those cases, the long value is greater than Integer.MAX_VALUE, that’s why the result value is wrapped with a negative number. If the long value is less than Integer.MIN_VALUE the result value is a positive number.

使用直接投掷,用lambda或使用装箱值会产生一个负值。在这些情况下,长值大于Integer.MAX_VALUE,这就是为什么结果值被包裹成一个负数。如果长值小于Integer.MIN_VALUE,结果值是一个正数。

On the other hand, three of the methods described in this article could throw different types of exceptions:

另一方面,本文描述的三个方法可能会抛出不同类型的异常。

@Test
public void longToIntIntegerException() {
    long max = Integer.MAX_VALUE + 10L;
    assertThrows(ArithmeticException.class, () -> ConvertLongToInt.longToIntWithBigDecimal(max));
    assertThrows(ArithmeticException.class, () -> ConvertLongToInt.longToIntJavaWithMath(max));
    assertThrows(IllegalArgumentException.class, () -> ConvertLongToInt.longToIntGuava(max));
}

For the first and the second one, an ArithmeticException is thrown. For the latter, an IllegalArgumentException is thrown. In that case, Ints.checkedCast checks if the integer is out of range.

对于第一个和第二个,会抛出一个ArithmeticException。对于后者,会抛出一个IllegalArgumentException。在这种情况下,Ints.checkedCast会检查整数是否超出了范围。

Finally, from Guava, the saturatedCast method, first check on integer limits and return the limit value is the passed number is greater or lower than the integer upper and lower bounds:

最后,来自Guava的saturatedCast方法,首先检查整数极限,并返回极限值,即传递的数字大于或小于整数的上、下限。

@Test
public void longToIntGuavaSaturated() {
    long max = Integer.MAX_VALUE + 10L;
    int expected = 2147483647;
    assertEquals(expected, ConvertLongToInt.longToIntGuavaSaturated(max));
}

3. Conclusion

3.总结

In this article, we went through some examples of how to convert long to int type in Java. Using native Java casting and some libraries.

在这篇文章中,我们通过一些例子来说明如何在Java中把long转换为int类型。使用本地的Java铸造和一些库。

As usual, all snippets used in this article are available over on GitHub.

像往常一样,本文中使用的所有片段都可以在GitHub上找到