問(wèn)題描述
有時(shí) java 讓我感到困惑.
我有大量的 int 初始化要做.
Sometimes java puzzles me.
I have a huge amount of int initializations to make.
真正的有什么區(qū)別?
Integer.toString(i)
new Integer(i).toString()
推薦答案
Integer.toString
調(diào)用類中的靜態(tài)方法 整數(shù)
.它不需要 Integer
的實(shí)例.
如果您調(diào)用 new Integer(i)
你創(chuàng)建了一個(gè) Integer
類型的實(shí)例,它是一個(gè)封裝了 int 值的完整 Java 對(duì)象.然后調(diào)用它的 toString
方法,要求它返回 itself 的字符串表示形式.
If you call new Integer(i)
you create an instance of type Integer
, which is a full Java object encapsulating the value of your int. Then you call the toString
method on it to ask it to return a string representation of itself.
如果你只想打印一個(gè)int
,你會(huì)使用第一個(gè),因?yàn)樗p、更快并且不使用額外的內(nèi)存(除了返回的字符串).
If all you want is to print an int
, you'd use the first one because it's lighter, faster and doesn't use extra memory (aside from the returned string).
如果您想要一個(gè)表示整數(shù)值的對(duì)象(例如將其放入集合中),您會(huì)使用第二個(gè),因?yàn)樗鼮槟峁┝艘粋€(gè)完整的對(duì)象來(lái)執(zhí)行您無(wú)法執(zhí)行的所有類型的事情一個(gè)簡(jiǎn)單的 int
.
If you want an object representing an integer value—to put it inside a collection for example—you'd use the second one, since it gives you a full-fledged object to do all sort of things that you cannot do with a bare int
.
這篇關(guān)于Java int to String - Integer.toString(i) vs new Integer(i).toString()的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!