Java 如何从 int 转换为 String?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4105331/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:40:25  来源:igfitidea点击:

How do I convert from int to String?

javastringtype-conversion

提问by Denis Palnitsky

I'm working on a project where all conversions from intto Stringare done like this:

我正在做一个项目,所有从int到到的转换String都是这样完成的:

int i = 5;
String strI = "" + i;

I'm not familiar with Java.

我不熟悉Java。

Is this usual practice or is something wrong, as I suppose?

我想这是通常的做法还是有什么问题?

采纳答案by SimonJ

Normal ways would be Integer.toString(i)or String.valueOf(i).

正常方式是Integer.toString(i)String.valueOf(i)

The concatenation will work, but it is unconventional and could be a bad smell as it suggests the author doesn't know about the two methods above (what else might they not know?).

串联会起作用,但它是非常规的并且可能是一种难闻的气味,因为它表明作者不知道上述两种方法(他们可能不知道还有什么?)。

Java has special support for the + operator when used with strings (see the documentation) which translates the code you posted into:

当与字符串一起使用时,Java 对 + 运算符有特殊支持(请参阅文档),它将您发布的代码转换为:

StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(i);
String strI = sb.toString();

at compile-time. It's slightly less efficient (sb.append()ends up calling Integer.getChars(), which is what Integer.toString()would've done anyway), but it works.

在编译时。它的效率稍低(sb.append()最终调用Integer.getChars()Integer.toString()无论如何都会这样做),但它有效。

To answer Grodriguez's comment: ** No, the compiler doesn'toptimise out the empty string in this case - look:

要回答 Grodriguez 的评论:** 不,在这种情况下,编译器不会优化空字符串 - 看:

simon@lucifer:~$ cat TestClass.java
public class TestClass {
  public static void main(String[] args) {
    int i = 5;
    String strI = "" + i;
  }
}
simon@lucifer:~$ javac TestClass.java && javap -c TestClass
Compiled from "TestClass.java"
public class TestClass extends java.lang.Object{
public TestClass();
  Code:
   0:    aload_0
   1:    invokespecial    #1; //Method java/lang/Object."<init>":()V
   4:    return

public static void main(java.lang.String[]);
  Code:
   0:    iconst_5
   1:    istore_1

Initialise the StringBuilder:

初始化 StringBuilder:

   2:    new    #2; //class java/lang/StringBuilder
   5:    dup
   6:    invokespecial    #3; //Method java/lang/StringBuilder."<init>":()V

Append the empty string:

附加空字符串:

   9:    ldc    #4; //String
   11:    invokevirtual    #5; //Method java/lang/StringBuilder.append:
(Ljava/lang/String;)Ljava/lang/StringBuilder;

Append the integer:

追加整数:

   14:    iload_1
   15:    invokevirtual    #6; //Method java/lang/StringBuilder.append:
(I)Ljava/lang/StringBuilder;

Extract the final string:

提取最终字符串:

   18:    invokevirtual    #7; //Method java/lang/StringBuilder.toString:
()Ljava/lang/String;
   21:    astore_2
   22:    return
}

There's a proposaland ongoing work to change this behaviour, targetted for JDK 9.

一个提议和正在进行的工作来改变这种行为,针对 JDK 9。

回答by darioo

It's not a good way.

这不是一个好方法。

When doing conversion from int to string, this should be used:

在进行从 int 到 string 的转换时,应该使用:

int i = 5;
String strI = String.valueOf(i);

回答by zneak

The other way I am aware of is from the Integerclass:

我知道的另一种方式是从Integer课堂上:

Integer.toString(int n);
Integer.toString(int n, int radix);

A concrete example (though I wouldn't think you need any):

一个具体的例子(虽然我认为你不需要任何):

String five = Integer.toString(5); // returns "5"

It also works for other primitive types, for instance Double.toString.

它也适用于其他原始类型,例如Double.toString.

See here for more details.

请参阅此处了解更多详情。

回答by duffymo

It's acceptable, but I've never written anything like that. I'd prefer this:

这是可以接受的,但我从来没有写过这样的东西。我更喜欢这个:

String strI = Integer.toString(i);

回答by ksu

Personally, I don't see anything bad in this code.

就我个人而言,我在这段代码中没有看到任何不好的地方。

It's pretty useful when you want to log an int value, and the logger just accepts a string. I would say such a conversion is convenient when you need to call a method accepting a String, but you have an int value.

当您想记录一个 int 值并且记录器只接受一个字符串时,它非常有用。当您需要调用接受字符串的方法时,我会说这样的转换很方便,但您有一个 int 值。

As for the choice between Integer.toStringor String.valueOf, it's all a matter of taste.
...And internally, the String.valueOfcalls the Integer.toStringmethod by the way. :)

至于在Integer.toString或之间的选择String.valueOf,这完全是一个品味问题。
...在内部,顺便String.valueOf调用该Integer.toString方法。:)

回答by Andreas Dolk

The expression

表达方式

"" + i

leads to string conversionof iat runtime. The overall type of the expression is String. iis first converted to an Integerobject (new Integer(i)), then String.valueOf(Object obj)is called. So it is equivalent to

导致字符串转换i在运行时。表达式的整体类型是Stringi首先转换为Integer对象 ( new Integer(i)),然后String.valueOf(Object obj)被调用。所以它等价于

"" + String.valueOf(new Integer(i));

Obviously, this is slightly less performant than just calling String.valueOf(new Integer(i))which will produce the very same result.

显然,这比仅调用String.valueOf(new Integer(i))会产生相同结果的性能稍差。

The advantage of ""+iis that typing is easier/faster and some people might think, that it's easier to read. It is not a code smellas it does not indicate any deeper problem.

的优点""+i是打字更容易/更快,有些人可能会认为,它更容易阅读。这不是代码异味,因为它并不表示任何更深层次的问题。

(Reference: JLS 15.8.1)

(参考:JLS 15.8.1

回答by Jay

Mostly ditto on SimonJ. I really dislike the ""+i idiom. If you say String.valueOf(i), Java converts the integer to a string and returns the result. If you say ""+i, Java creates a StringBuilder object, appends an empty string to it, converts the integer to a string, appends this to the StringBuilder, then converts the StringBuilder to a String. That's a lot of extra steps. I suppose if you do it once in a big program, it's no big deal. But if you're doing this all the time, you're making the computer do a bunch of extra work and creating all these extra objects that then have to be cleaned up. I don't want to get fanatic about micro-optimization, but I don't want to be pointlessly wasteful either.

主要是在 SimonJ 上同上。我真的不喜欢 ""+i 成语。如果您说 String.valueOf(i),Java 会将整数转换为字符串并返回结果。如果您说 ""+i,Java 将创建一个 StringBuilder 对象,向其附加一个空字符串,将整数转换为字符串,将其附加到 StringBuilder,然后将 StringBuilder 转换为 String。这是很多额外的步骤。我想如果你在一个大程序中做一次,那没什么大不了的。但如果你一直这样做,你就会让计算机做一堆额外的工作,并创建所有这些额外的对象,然后必须清理它们。我不想狂热于微优化,但我也不想毫无意义地浪费。

回答by user85421

It's not only the optimization1. I don't like

这不仅仅是优化1。我不喜欢

"" + i

because it does not express what I really want to do 2.

因为它没有表达我真正想做的事情2.

I don't want to append an integer to an (empty) string. I want to convert an integer to string:

我不想将整数附加到(空)字符串中。我想将整数转换为字符串:

Integer.toString(i)

Or, not my prefered, but still better than concatenation, get a string representation of an object (integer):

或者,不是我喜欢的,但仍然比串联更好,获取对象的字符串表示(整数):

String.valueOf(i)

1. For code that is called very often, like in loops, optimization sure is also a point for not using concatenation.

1.对于经常调用的代码,比如在循环中,优化当然也是不使用 concatenation 的一个要点

2. this is not valid for use ofreal concatenation like inSystem.out.println("Index: " + i);orString id = "ID" + i;

2.这不是有效的使用真正的串联像System.out.println("Index: " + i);String id = "ID" + i;

回答by GreenMatt

This technique was taught in an undergraduate level introduction-to-Java class I took over a decade ago. However, I should note that, IIRC, we hadn't yet gotten to the String and Integer class methods.

十多年前,我在本科级别的 Java 入门课程中教授了这项技术。但是,我应该注意到,IIRC,我们还没有接触到 String 和 Integer 类方法。

The technique is simple and quick to type. If all I'm doing is printing something, I'll use it (for example, System.out.println("" + i);. However, I think it's not the best way to do a conversion, as it takes a second of thought to realize what's going on when it's being used this way. Also, if performance is a concern, it seems slower (more below, as well as in other answers).

该技术简单且可快速打字。如果我做的是打印的东西,我将使用它(例如,System.out.println("" + i);不过,我认为这不是做一个转换的最佳途径,因为它需要思考的第二个认识是怎么回事了所使用的时候它这样。另外,如果性能是一个问题,它似乎更慢(更多在下面,以及在其他答案中)。

Personally, I prefer Integer.toString(), as it is obvious what's happening. String.valueOf() would be my second choice, as it seems to be confusing (witness the comments after darioo's answer).

就个人而言,我更喜欢 Integer.toString(),因为很明显发生了什么。String.valueOf() 将是我的第二选择,因为它似乎令人困惑(见证 darioo 回答后的评论)。

Just for grins :) I wrote up classes to test the three techniques: "" + i, Integer.toString, and String.ValueOf. Each test just converted the ints from 1 to 10000 to Strings. I then ran each through the Linux timecommand five times. Integer.toString() was slightly faster than String.valueOf() once, they tied three times, and String.valueOf() was faster once; however, the difference was never more than a couple of milliseconds.

只是为了咧嘴笑:) 我编写了类来测试三种技术:"" + i、Integer.toString 和 String.ValueOf。每个测试只是将整数从 1 转换为 10000 到字符串。然后我通过 Linux时间命令分别运行了五次。Integer.toString() 比 String.valueOf() 稍快一次,他们并列了 3 次,String.valueOf() 快了一次;然而,差异从未超过几毫秒。

The "" + i technique was slower than both on every test except one, when it was 1 millisecond faster than Integer.toString() and 1 millisecond slower than String.valueOf() (obviously on the same test where String.valueOf() was faster than Integer.toString()). While it was usually only a couple milliseconds slower, there was one test where it was about 50 milliseconds slower. YMMV.

"" + i 技术在每个测试中都比这两个测试都慢,除了一个,它比 Integer.toString() 快 1 毫秒,比 String.valueOf() 慢 1 毫秒(显然在同一个测试中 String.valueOf()比 Integer.toString() 快。虽然它通常只慢几毫秒,但有一个测试表明它慢了大约 50 毫秒。天啊

回答by Konrad Rudolph

A lot of introductory University courses seem to teach this style, for two reasons (in my experience):

许多介绍性大学课程似乎都教授这种风格,原因有二(以我的经验):

  • It doesn't require understanding of classes or methods. Usually, this is taught way before the word “class” is ever mentioned – nor even method calls. So using something like String.valueOf(…)would confuse students.

  • It is an illustration of “operator overloading” – in fact, this was sold to us as theidiomatic overloaded operator (small wonder here, since Java doesn't allow custom operator overloading).

  • 它不需要了解类或方法。通常,这是在提到“类”这个词之前教过的——甚至没有提到方法调用。所以使用类似的东西String.valueOf(…)会让学生感到困惑。

  • 它是“操作符重载”的一个例子——事实上,这是作为惯用的重载操作符卖给我们(这没什么奇怪的,因为 Java 不允许自定义操作符重载)。

So it may either be born out of didactic necessity (although I'd argue that this is just bad teaching) or be used to illustrate a principle that's otherwise quite hard to demonstrate in Java.

因此,它可能是出于教学需要(尽管我认为这只是糟糕的教学)或用于说明在 Java 中很难演示的原则。