Convert String to int or Integer in Java – 在Java中把字符串转换成int或Integer

最后修改: 2016年 8月 31日

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

1. Introduction

1.介绍

Converting a String to an int or Integer is a very common operation in Java. In this article, we will show multiple ways of dealing with this issue.

字符串转换为intInteger是Java中一个非常常见的操作。在这篇文章中,我们将展示处理这个问题的多种方法。

There are a few simple ways to tackle this basic conversion.

有几个简单的方法来解决这个基本的转换。

2. Integer.parseInt()

2.Integer.parseInt()

One of the main solutions is to use Integer‘s dedicated static method: parseInt(), which returns a primitive int value:

其中一个主要的解决方案是使用Integer的专用静态方法。parseInt(),它返回一个原始的int

@Test
public void givenString_whenParsingInt_shouldConvertToInt() {
    String givenString = "42";

    int result = Integer.parseInt(givenString);

    assertThat(result).isEqualTo(42);
}

By default, the parseInt() method assumes the given String is a base-10 integer. Additionally, this method accepts another argument to change this default radix. For instance, we can parse binary Strings as follows:

默认情况下,parseInt()方法假定给定的字符串是一个base-10的整数。此外,这个方法还接受另一个参数来改变这个默认的radix。例如,我们可以如下解析二进制的Strings:

@Test
public void givenBinaryString_whenParsingInt_shouldConvertToInt() {
    String givenString = "101010";

    int result = Integer.parseInt(givenString, 2);

    assertThat(result).isEqualTo(42);
}

Naturally, it’s also possible to use this method with any other radix such as 16 (hexadecimal) or 8 (octal).

当然,这种方法也可以用在任何其他小数上,如16(十六进制)或8(八进制)。

3. Integer.valueOf()

3.Integer.valueOf()

Another option would be to use the static Integer.valueOf() method, which returns an Integer instance:

另一个选择是使用静态的Integer.valueOf()方法,它返回一个Integer实例

@Test
public void givenString_whenCallingIntegerValueOf_shouldConvertToInt() {
    String givenString = "42";

    Integer result = Integer.valueOf(givenString);

    assertThat(result).isEqualTo(new Integer(42));
}

Similarly, the valueOf() method also accepts a custom radix as the second argument:

同样地,valueOf()方法也接受一个自定义的radix作为第二个参数。

@Test
public void givenBinaryString_whenCallingIntegerValueOf_shouldConvertToInt() {
    String givenString = "101010";

    Integer result = Integer.valueOf(givenString, 2);

    assertThat(result).isEqualTo(new Integer(42));
}

3.1. Integer Cache

3.1 整数缓存

At first glance, it may seem that the valueOf() and parseInt() methods are exactly the same. For the most part, this is true — even the valueOf() method delegates to the parseInt method internally.

乍一看,似乎valueOf()parseInt()方法是完全相同的。在大多数情况下,这是真的 – 甚至valueOf()方法在内部也委托给parseInt方法。

However, there is one subtle difference between these two methods: the valueOf() method is using an integer cache internally. This cache would return the same Integer instance for numbers between -128 and 127:

然而,这两个方法之间有一个微妙的区别。valueOf()方法内部使用一个整数缓存。这个缓存将为-128和127之间的数字返回同一个Integer实例

@Test
public void givenString_whenCallingValueOf_shouldCacheSomeValues() {
    for (int i = -128; i <= 127; i++) {
        String value = i + "";
        Integer first = Integer.valueOf(value);
        Integer second = Integer.valueOf(value);

        assertThat(first).isSameAs(second);
    }
}

Therefore, it’s highly recommended to use valueOf() instead of parseInt() to extract boxed integers as it may lead to a better overall footprint for our application.

因此,强烈建议使用valueOf()而不是parseInt()来提取带框的整数,因为这可能会给我们的应用程序带来更好的整体足迹。

4. Integer‘s Constructor

4、Integer的构造函数

You could also use Integer‘s constructor:

你也可以使用Integer的构造函数。

@Test
public void givenString_whenCallingIntegerConstructor_shouldConvertToInt() {
    String givenString = "42";

    Integer result = new Integer(givenString);

    assertThat(result).isEqualTo(new Integer(42));
}

As of Java 9, this constructor has been deprecated in favor of other static factory methods such as valueOf() or parseInt(). Even before this deprecation, it was rarely appropriate to use this constructor. We should use parseInt() to convert a string to an int primitive or use valueOf() to convert it to an Integer object.

从Java 9开始,这个构造函数已经被弃用,转而使用其他静态工厂方法,如valueOf()parseInt()。即使在这次弃用之前,使用这个构造函数也是很少见的。我们应该使用parseInt()来将字符串转换为int基元,或者使用valueOf()来将其转换为Integer对象。

5. Integer.decode()

5 Integer.decode()

Also, Integer.decode() works similarly to the Integer.valueOf(), but can also accept different number representations:

另外,Integer.decode()的工作原理与Integer.valueOf()类似,但也可以接受不同的数字表示法

@Test
public void givenString_whenCallingIntegerDecode_shouldConvertToInt() {
    String givenString = "42";

    int result = Integer.decode(givenString);

    assertThat(result).isEqualTo(42);
}

6. NumberFormatException

6.NumberFormatException

All mentioned above methods throw a NumberFormatException, when encountering unexpected String values. Here you can see an example of such a situation:

所有上述方法在遇到意外的String值时都会抛出NumberFormatException。在这里你可以看到这种情况的一个例子。

@Test(expected = NumberFormatException.class)
public void givenInvalidInput_whenParsingInt_shouldThrow() {
    String givenString = "nan";
    Integer.parseInt(givenString);
}

7. With Guava

7.有番石榴

Of course, we do not need to stick to the core Java itself. This is how the same thing can be achieved using Guava’s Ints.tryParse(), which returns a null value if it cannot parse the input:

当然,我们不需要拘泥于核心Java本身。这就是使用Guava的Ints.tryParse()可以实现同样的事情,如果不能解析输入,它将返回一个null值。

@Test
public void givenString_whenTryParse_shouldConvertToInt() {
    String givenString = "42";

    Integer result = Ints.tryParse(givenString);

    assertThat(result).isEqualTo(42);
}

Moreover, the tryParse() method also accepts a second radix argument similar to parseInt() and valueOf().

此外,tryParse()方法也接受第二个radix参数,类似于parseInt()valueOf()。

8. Conclusion

8.结论

In this article, we have explored multiple ways of converting String instances to int or Integer instances.

在这篇文章中,我们探讨了将String实例转换为intInteger实例的多种方法。

All code examples can, of course, be found over on GitHub.

当然,所有的代码实例都可以在GitHub上找到