如何从int转换为String? [英] How do I convert from int to String?

查看:117
本文介绍了如何从int转换为String?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个项目,其中从 int String 的所有转换都是这样完成的:

I'm working on a project where all conversions from int to String are done like this:

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

我不熟悉Java。这是通常的做法还是有问题,正如我想的那样?

I'm not familiar with Java. Is this usual practice or is something wrong, as I suppose?

推荐答案

正常方式是整数。 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对+运算符有特殊支持(参见文档)翻译您发布的代码:

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

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

在编译时。它的效率稍差( sb.append()最终调用 Integer.getChars(),这就是 Integer.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.

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

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

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

初始化StringBuilder:

Initialise the StringBuilder:

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

附加空字符串:

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

追加整数:

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

提取最终字符串:

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

有< a href =https://bugs.openjdk.java.net/browse/JDK-8085796\"rel =noreferrer>提案和正在进行的改变此行为的工作,针对JDK  9。

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

这篇关于如何从int转换为String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆