java 为什么我应该使用 Integer.toString() 而不是只打印 Integer?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14126792/
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
Why should I use Integer.toString() instead of just printing the Integer?
提问by Mike
I was following a Java tutorial and it was having me do something like:
我正在学习 Java 教程,它让我做类似的事情:
int k = 5;
System.out.println("The number is " + Integer.toString(k));
So like a good sport I followed along, but I can't help but wonder, why use that method at all? Seems like a lot of extra typing to get the same functionality as:
所以就像我遵循的一项好运动,但我不禁想知道,为什么要使用这种方法?似乎有很多额外的输入来获得与以下相同的功能:
int k = 5;
System.out.println("The number is " + k);
Is there a good reason to use the toString()
method for non-string data types? And in my specific example, are there any int
values that can't be auto toString'ed?
toString()
对非字符串数据类型使用该方法是否有充分的理由?在我的具体示例中,是否有任何int
值不能自动 toString ?
回答by rob
It's one of many "safe programming" practices you can adopt to improve clarity and prevent subtle errors which you or a future maintainer of your code could introduce. Take the following example:
这是您可以采用的许多“安全编程”实践之一,以提高清晰度并防止您或您的代码的未来维护者可能引入的细微错误。以下面的例子为例:
private static void printMessage(int k) {
System.out.println("number" + '=' + k);
}
output: number=5
输出: number=5
Now suppose you want to print the number first and the text last. All I'm doing is swapping the first and last items in the string concatenation:
现在假设你想先打印数字,最后打印文本。我所做的只是交换字符串连接中的第一个和最后一个项目:
private static void printMessage2(int k) {
System.out.println(k + '=' + "number");
}
output: 66number
输出: 66number
Oops! The int value of =
was added to k
instead of being concatenated. One solution is to make the =
into a String
. Another solution is to explicitly convert the int
to a String
:
哎呀!的 int 值=
被添加到k
而不是被连接。一个解决办法是让=
成String
。另一种解决方案是将 the 显式转换int
为 a String
:
private static void printMessage2Safe(int k) {
System.out.println(Integer.toString(k) + '=' + "number");
}
output: 5=number
输出: 5=number
"Oh, but I'd never do that, anyway," you say. "Anyone in their right mind would have just made the =
part of the other String." But what if you're implementing part of a basic calculator app, and you want to output the expression and its result? If you're really trying to be careful, I suppose you'll use StringBuilder.append()
to concatenate the parts of the expression. But if not, then I hope you don't write the first implementation of the display
method below.
“哦,但无论如何,我永远不会那样做,”你说。“任何头脑正常的人都会制作=
另一个字符串的一部分。” 但是,如果您正在实现基本计算器应用程序的一部分,并且想要输出表达式及其结果,该怎么办?如果您真的很小心,我想您会使用StringBuilder.append()
来连接表达式的各个部分。但是如果没有,那么希望你不要写display
下面方法的第一个实现。
public class Calculator {
public static void main(String[] args) {
display(2, '+', 3, 5);
displaySafe(2, '+', 3, 5);
}
public static void display(int num1, char operator, int num2, int result) {
System.out.println(num1 + operator + num2 + '=' + result);
}
public static void displaySafe(int num1, char operator, int num2, int result) {
System.out.println(Integer.toString(num1) + operator + Integer.toString(num2) + "=" + result);
}
}
output:
输出:
114
2+3=5
回答by Peter Lawrey
Is there a good reason to use the toString() method for non-string data types?
对非字符串数据类型使用 toString() 方法是否有充分的理由?
Some people believe it is clearer. esp for beginners who may not realised they do basically the same thing.
有些人认为它更清楚。尤其是对于可能没有意识到他们做的事情基本上相同的初学者。
Note: In Java 7 update 9, it doesn't create the String first as append(int) looks like this
注意:在 Java 7 update 9 中,它不会首先创建字符串,因为 append(int) 看起来像这样
// from AbstractStringBuilder
public AbstractStringBuilder append(int i) {
if (i == Integer.MIN_VALUE) {
append("-2147483648");
return this;
}
int appendedLength = (i < 0) ? Integer.stringSize(-i) + 1
: Integer.stringSize(i);
int spaceNeeded = count + appendedLength;
ensureCapacityInternal(spaceNeeded);
Integer.getChars(i, spaceNeeded, value);
count = spaceNeeded;
return this;
}
It converts the number strait into the StringBuilder avoiding the need to create a String first.
它将数字海峡转换为 StringBuilder,避免了首先创建 String 的需要。
And in my specific example, are there any int values that can't be auto toString'ed?
在我的具体示例中,是否有任何不能自动 toString 的 int 值?
No. All primitive values can be toString'ed.
不可以。所有原始值都可以是 toString 的。
The only exception I know of is signalling and quiet Not-A-Numbervalues as Java doesn't care about such things. Both appear as "NaN" and there is no way to tell the difference from the toString() (or most functions in Java)
我所知道的唯一例外是信号和安静的 Not-A-Number值,因为 Java 不关心这些事情。两者都显示为“NaN”并且无法区分与 toString() (或 Java 中的大多数函数)
回答by Android Killer
System.out.println("The number is " + Integer.toString(k));
In the above print "The number is "is string, so String+(anything)is Stringonly.So in that case no need to call toString() at all.So if you want to print k value only then also no need to call toString() as S.O.P
internaqlly calls toString().
在上面打印“数字是”是字符串,所以字符串+(任何东西)只是字符串。所以在这种情况下根本不需要调用toString()。所以如果你只想打印k值那么也不需要调用toString() 作为S.O.P
内部调用 toString()。
So finally , we can say unless specifically you want to convert Integer to String you should not call toString() method.
所以最后,我们可以说除非你特别想将 Integer 转换为 String 你不应该调用 toString() 方法。
回答by Evgeniy Dorofeev
Use the second version. For string concatination expressions like
使用第二个版本。对于字符串连接表达式,如
"The number is " + k;
javac builds the actual code using StringBuilder as
javac 使用 StringBuilder 构建实际代码作为
new StringBuilder("The number is ")).append(Integer.toString(k)).toString());
so System.out.println simply prints the resulting string, the full code is
所以 System.out.println 只是打印结果字符串,完整的代码是
System.out.println((new StringBuilder("The number is ")).append(Integer.toString(k)).toString());
回答by Dustin Koeller
It allows the number to become a String data type so it is all a string. As Mob said though, it's not even an integer to start with. You would have to parse it to an integer before it would become one.
它允许数字成为字符串数据类型,因此它都是字符串。正如 Mob 所说,它甚至不是一个整数。您必须先将其解析为整数,然后才能变为 1。