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

查看:222
本文介绍了Java int to String - Integer.toString(i)vs new Integer(i).toString()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时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()

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


推荐答案

Integer.toString 调用类中的静态方法 整数 。它不需要 Integer 的实例。

如果你打电话给 new Integer(i) 您创建一个类型为 Integer 的实例,这是一个封装int值的完整Java对象。然后在其上调用 toString 方法,要求它返回本身的字符串表示

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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆