Java int to String - Integer.toString(i) vs new Integer(i).toString()(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.
真正的有什么区别?
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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java int to String - Integer.toString(i) vs new Integer(i).toString()


- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01