問題描述
有時 java 讓我感到困惑.
我有大量的 int 初始化要做.
Sometimes java puzzles me.
I have a huge amount of int initializations to make.
真正的有什么區別?
Integer.toString(i)
new Integer(i).toString()
推薦答案
Integer.toString
調用類中的靜態方法 整數
.它不需要 Integer
的實例.
如果您調用 new Integer(i)
你創建了一個 Integer
類型的實例,它是一個封裝了 int 值的完整 Java 對象.然后調用它的 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.
如果你只想打印一個int
,你會使用第一個,因為它更輕、更快并且不使用額外的內存(除了返回的字符串).
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).
如果您想要一個表示整數值的對象(例如將其放入集合中),您會使用第二個,因為它為您提供了一個完整的對象來執行您無法執行的所有類型的事情一個簡單的 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
.
這篇關于Java int to String - Integer.toString(i) vs new Integer(i).toString()的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!