Java Integer.toString(int i) vs String.valueOf(int i)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3335737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Integer.toString(int i) vs String.valueOf(int i)
提问by Manuel Selva
I am wondering why the method String.valueOf(int i)
exists ? I am using this method to convert int
into String
and just discovered the Integer.toString(int i)
method.
我想知道为什么该方法String.valueOf(int i)
存在?我正在使用此方法转换int
为String
并刚刚发现该Integer.toString(int i)
方法。
After looking the implementation of these methods I saw that the first one is calling the second one. As a consequence all my calls to String.valueOf(int i)
involve one more call than directly calling Integer.toString(int i)
查看这些方法的实现后,我看到第一个正在调用第二个。因此,我所有的String.valueOf(int i)
电话都比直接打电话多一个电话Integer.toString(int i)
采纳答案by mipadi
Just two different ways of doing the same thing. It may be a historical reason (can't remember if one came before the other).
只是做同一件事的两种不同方式。这可能是一个历史原因(不记得一个是否在另一个之前)。
回答by polygenelubricants
You shouldn't worry about this extra call costing you efficiency problems. If there's any cost, it'll be minimal, and should be negligible in the bigger picture of things.
您不必担心这个额外的通话会导致效率问题。如果有任何成本,它将是最小的,并且在更大的事物中应该可以忽略不计。
Perhaps the reason why both exist is to offer readability. In the context of many types being converted to String
, then various calls to String.valueOf(SomeType)
may be more readable than various SomeType.toString
calls.
也许两者存在的原因是为了提供可读性。在许多类型被转换为 的上下文中String
,那么各种对 的调用String.valueOf(SomeType)
可能比各种SomeType.toString
调用更具可读性。
回答by Kingo
The String class provides valueOf methods for all primitive types and Object type so I assume they are convenience methods that can all be accessed through the one class.
String 类为所有原始类型和 Object 类型提供了 valueOf 方法,因此我假设它们是可以通过一个类访问的便捷方法。
NB Profiling results
NB 分析结果
Average intToString = 5368ms, Average stringValueOf = 5689ms (for 100,000,000 operations)
平均 intToString = 5368 毫秒,平均 stringValueOf = 5689 毫秒(对于 100,000,000 次操作)
public class StringIntTest {
public static long intToString () {
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
String j = Integer.toString(i);
}
long finishTime = System.currentTimeMillis();
return finishTime - startTime;
}
public static long stringValueOf () {
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
String j = String.valueOf(i);
}
long finishTime = System.currentTimeMillis();
return finishTime - startTime;
}
public static void main(String[] args) {
long intToStringElapsed = 0;
long stringValueOfElapsed = 0;
for (int i = 0; i < 10; i++) {
intToStringElapsed += intToString();
stringValueOfElapsed+= stringValueOf();
}
System.out.println("Average intToString = "+ (intToStringElapsed /10));
System.out.println("Average stringValueOf = " +(stringValueOfElapsed / 10));
}
}
回答by trashgod
The implementation of String.valueOf()
that you see is the simplest way to meet the contract specified in the API: "The representation is exactly the one returned by the Integer.toString()
method of one argument."
String.valueOf()
您看到的实现是满足 API 中指定的契约的最简单方法:“表示正是由Integer.toString()
一个参数的方法返回的表示。”
回答by Damian Leszczyński - Vash
In String type we have several method valueOf
在 String 类型中,我们有几个方法 valueOf
static String valueOf(boolean b)
static String valueOf(char c)
static String valueOf(char[] data)
static String valueOf(char[] data, int offset, int count)
static String valueOf(double d)
static String valueOf(float f)
static String valueOf(int i)
static String valueOf(long l)
static String valueOf(Object obj)
As we can see those method are capable to resolve all kind of numbers
正如我们所看到的,这些方法能够解析所有类型的数字
every implementation of specific method like you have presented: So for integers we have
像您介绍的特定方法的每个实现:所以对于整数,我们有
Integer.toString(int i)
for double
双人
Double.toString(double d)
and so on
等等
In my opinion this is not some historical thing, but it is more useful for a developer to use the method valueOf
from the String class than from the proper type, as it leads to fewer changes for us to make.
在我看来,这不是什么历史事件,但对于开发人员来说,使用valueOf
String 类中的方法比使用正确类型的方法更有用,因为它导致我们要做的更改更少。
Sample 1:
示例 1:
public String doStuff(int num) {
// Do something with num...
return String.valueOf(num);
}
Sample2:
样本2:
public String doStuff(int num) {
// Do something with num...
return Integer.toString(num);
}
As we see in sample 2 we have to do two changes, in contrary to sample one.
正如我们在示例 2 中看到的,与示例一相反,我们必须进行两次更改。
In my conclusion, using the valueOf
method from String class is more flexible and that's why it is available there.
在我的结论中,使用valueOf
String 类中的方法更灵活,这就是它在那里可用的原因。
回答by tskuzzy
If you look at the source code for the String
class, it actually calls Integer.toString()
when you call valueOf()
.
如果您查看String
该类的源代码,它实际上会Integer.toString()
在您调用valueOf()
.
That being said, Integer.toString()
might be a tad faster if the method calls aren't optimized at compile time (which they probably are).
话虽如此,Integer.toString()
如果在编译时未优化方法调用(它们可能是),则可能会快一点。
回答by A Costa
One huge difference is that if you invoke toString()
in a null object you'll get a NullPointerException
whereas, using String.valueOf()
you may not check for null.
一个巨大的区别是,如果你toString()
在一个空对象中调用你会得到一个NullPointerException
while,使用String.valueOf()
你可能不会检查 null。
回答by Amit Bhandari
Using the method, String.valueOf() you do not have to worry about the data(whether it is int,long,char,char[],boolean,Object), you can just call :
使用 String.valueOf() 方法您不必担心数据(无论是 int,long,char,char[],boolean,Object),您只需调用:
- static String valueOf()
- 静态字符串 valueOf()
using the only syntax String.valueOf() can whatever you pass as a parameter is converted to String and returned..
使用唯一的语法 String.valueOf() 可以将您作为参数传递的任何内容转换为 String 并返回..
Otherwise, if you use Integer.toString(),Float.toString() etc.(i.e. SomeType.toString()) then you will have to check the datatype of parameter that you want to convert into string. So, its better to use String.valueOf() for such convertions.
否则,如果您使用 Integer.toString(),Float.toString() 等(即 SomeType.toString()),则您必须检查要转换为字符串的参数的数据类型。因此,最好使用 String.valueOf() 进行此类转换。
If you are having an array of object class that contains different values like Integer,Char,Float etc. then by using String.valueOf() method you can convert the elements of such array into String form easily. On contrary, if you want to use SomeType.toString() then at first you will need to know about there their datatype classes(maybe by using "instanceOf" operator) and then only you can proceed for a typecast.
如果您有一个包含不同值(如 Integer、Char、Float 等)的对象类数组,那么通过使用 String.valueOf() 方法,您可以轻松地将此类数组的元素转换为 String 形式。相反,如果您想使用 SomeType.toString() ,那么首先您需要了解它们的数据类型类(可能通过使用“instanceOf”运算符),然后只有您才能进行类型转换。
String.valueOf() method when called matches the parameter that is passed(whether its Integer,Char,Float etc.) and by using method overloading calls that "valueOf()" method whose parameter gets matched, and then inside that method their is a direct call to corresponding "toString()" method..
String.valueOf() 方法在调用时匹配传递的参数(无论是 Integer、Char、Float 等),并通过使用方法重载调用其参数匹配的“valueOf()”方法,然后在该方法中它们是直接调用相应的“toString()”方法..
So, we can see how the overhead of checking datatype and then calling corresponding "toString()" method is removed.Only we need is to call String.valueOf() method, not caring about what we want to convert to String.
这样,我们就可以看到检查数据类型然后调用相应的“toString()”方法的开销是如何被去除的。我们只需要调用String.valueOf()方法,而不关心我们要转换为String。
Conclusion: String.valueOf() method has its importance just at cost of one more call.
结论: String.valueOf() 方法的重要性只是以再调用一次为代价。
回答by shruti
toString()
toString()
- is present in Object class, generally overrided in derived class
- typecast to appropriate class is necessary to call toString() method.
- 存在于 Object 类中,通常在派生类中被覆盖
- 调用 toString() 方法需要将类型转换为适当的类。
valueOf()
的价值()
- Overloaded static method present in String class.
handles primitive types as well as object types.
Integer a = null; System.out.println(Integer.toString()) ; NUll pointer exception System.out.println(String.valueOf() ; give NULL as value
- String 类中存在重载的静态方法。
处理原始类型和对象类型。
Integer a = null; System.out.println(Integer.toString()) ; NUll pointer exception System.out.println(String.valueOf() ; give NULL as value
check this link its very good. http://code4reference.com/2013/06/which-one-is-better-valueof-or-tostring/
检查此链接非常好。http://code4reference.com/2013/06/which-one-is-better-valueof-or-tostring/
回答by anuragsingh
my openion is valueof() always called tostring() for representaion and so for rpresentaion of primtive type valueof is generalized.and java by default does not support Data type but it define its work with objaect and class its made all thing in cllas and made object .here Integer.toString(int i) create a limit that conversion for only integer.
我的 openion 是 valueof() 总是调用 tostring() 来表示,因此对于原始类型的 rpresentaion valueof 是通用的。默认情况下,java 不支持数据类型,但它定义了它与对象和类的工作,它在 cllas 中制作了所有东西并制作object .here Integer.toString(int i) 创建一个限制,只能转换为整数。