简体   繁体   English

为什么我应该使用Integer.toString()而不是只打印Integer?

[英]Why should I use Integer.toString() instead of just printing the Integer?

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? 是否有充分的理由对非字符串数据类型使用toString()方法? And in my specific example, are there any int values that can't be auto toString'ed? 在我的具体示例中,是否有任何int值不能自动toString?

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. =的int值被添加到k而不是连接。 One solution is to make the = into a String . 一种解决方案是将=变为String Another solution is to explicitly convert the int to a String : 另一种解决方案是将int显式转换为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. 如果你真的要小心,我想你会使用StringBuilder.append()来连接表达式的各个部分。 But if not, then I hope you don't write the first implementation of the display method below. 但如果没有,那么我希望你不要编写下面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

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. esp对于那些可能没有意识到他们基本上做同样事情的初学者。

Note: In Java 7 update 9, it doesn't create the String first as append(int) looks like this 注意:在Java 7更新9中,它不会首先创建String,因为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. 它将数字strait转换为StringBuilder,避免了首先创建String的需要。

And in my specific example, are there any int values that can't be auto toString'ed? 在我的具体示例中,是否有任何int值不能自动toString?

No. All primitive values can be toString'ed. 不。所有原始值都可以是toString。

The only exception I know of is signalling and quiet Not-A-Number values as Java doesn't care about such things. 我所知道的唯一例外是信令和安静的Not-A-Number值,因为Java并不关心这些事情。 Both appear as "NaN" and there is no way to tell the difference from the toString() (or most functions in Java) 两者都显示为“NaN”,并且无法区分toString()(或Java中的大多数函数)

System.out.println("The number is " + Integer.toString(k));

In the above print "The number is " is string, so String+(anything) is String only.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 SOP internaqlly calls toString(). 在上面的打印“数字是”是字符串,所以字符串+(任何)只是字符串。所以在这种情况下,根本不需要调用toString()。所以如果你想打印k值,那么也不需要调用toString()as SOP internaqlly调用toString()。

So finally , we can say unless specifically you want to convert Integer to String you should not call toString() method. 所以最后,我们可以说除非特别想要将Integer转换为String,否则不应该调用toString()方法。

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());

It allows the number to become a String data type so it is all a string. 它允许数字成为String数据类型,因此它都是一个字符串。 As Mob said though, it's not even an integer to start with. 正如Mob所说,它甚至不是一个整数。 You would have to parse it to an integer before it would become one. 在成为一个整数之前,你必须将它解析为整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM