Java int to String - Integer.toString(i)vs new Integer(i).toString()

本文翻译自:Java int to String - Integer.toString(i) vs new Integer(i).toString()

Sometimes java puzzles me. 有时java困惑我。
I have a huge amount of int initializations to make. 我有大量的int初始化。

What's the real difference? 真正的区别是什么?

  1. Integer.toString(i)
  2. new Integer(i).toString()

#1楼

参考:https://stackoom.com/question/GUQU/Java-int-to-String-Integer-toString-i-vs-new-Integer-i-toString


#2楼

I also highly recommend using 我也强烈推荐使用

int integer = 42;
String string = integer + "";

Simple and effective. 简单有效。


#3楼

更好:

Integer.valueOf(i).toString()

#4楼

Another option is the static String.valueOf method. 另一个选项是静态String.valueOf方法。

String.valueOf(i)

It feels slightly more right than Integer.toString(i) to me. 感觉Integer.toString(i)对我更正确。 When the type of i changes, for example from int to double , the code will stay correct. 当i的类型改变时,例如从int变为double ,代码将保持正确。


#5楼

Here Integer.toString calls the static method in the class Integer. 这里Integer.toString调用Integer类中的静态方法。 It does not require the object to call. 它不需要对象调用。

If you call new Integer(i) you first create an instance of type Integer, which is a full Java object encapsulating the value of your int i. 如果调用new Integer(i) ,首先要创建一个Integer类型的实例,它是一个封装int i值的完整Java对象。 Then you call the toString method on it to ask it to return a string representation of itself. 然后在其上调用toString方法,要求它返回自身的字符串表示。


#6楼

Although I like fhucho's recommendation of 虽然我喜欢fhucho的推荐

String.valueOf(i)

The irony is that this method actually calls 具有讽刺意味的是,这种方法实际上是召唤

Integer.toString(i)

Thus, use String.valueOf(i) if you like how it reads and you don't need radix, but also knowing that it is less efficient than Integer.toString(i) . 因此,如果您喜欢它的读取方式并且不需要基数,请使用String.valueOf(i) ,但也要知道它的效率低于Integer.toString(i)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值