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

2022-01-14 00:00:00 string int java

有时 java 让我感到困惑.
我有大量的 int 初始化要做.

Sometimes java puzzles me.
I have a huge amount of int initializations to make.

真正的有什么区别?

  1. Integer.toString(i)
  2. 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.

相关文章