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

查看:18
本文介绍了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()

推荐答案

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

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