Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

java - 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()
  ask by marcolopes translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Integer.toString calls the static method in the class Integer . (Integer.toString调用Integer类中的静态方法。) It does not need an instance of Integer . (它不需要Integer的实例。)

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. (如果调用new Integer(i) ,则创建一个Integer类型的实例,它是一个封装int值的完整Java对象。) Then you call the toString method on it to ask it to return a string representation of itself . (然后在其上调用toString方法,要求它返回自身的字符串表示。)

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 . (如果你想要一个表示整数值的对象 - 例如将它放在一个集合中 - 你会使用第二个,因为它为你提供了一个完整的对象来完成你无法用裸int做的所有事情。 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...