Integer.parseInt()优于Integer构造函数的优点

时间:2015-09-30 13:49:42

标签: java

我们可以直接进行以下转换:

String s="123";
int a=new Integer(s);

那么使用Integer.parseInt()方法有什么好处?

2 个答案:

答案 0 :(得分:3)

整数构造函数在内部调用parseInt,返回int。如果直接调用parseInt,则应避免自动装箱(构造函数返回Integer)。

public Integer(String s) throws NumberFormatException {
    this.value = parseInt(s, 10);
}

同样使用parseInt,您可以使用不同于10的基数来解析字符串。例如:

int hex = Integer.parseInt("FF", 16); // 255
int bin = Integer.parseInt("10", 2); // 2

答案 1 :(得分:1)

在您的示例中,您(隐式地)执行了一个额外的装箱操作(对Integer}对象),使用Integer.parseInt时可以避免这种操作。 Integer.parseInt直接从您的输入int中为您提供String

基本上你的代码相当于:

String s = "123";
int a = (new Integer(s)).intValue(); 

如您所见,您实际上并不需要new Integer(s)个对象,
您只需要将原始int值存储在其中。

相关问题