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

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

问题描述

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

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

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

我不熟悉 Java.

这是通常的做法还是我认为有问题?

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

推荐答案

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

Normal ways would be Integer.toString(i) or 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
}

一项提议,并且正在进行改变这种行为的工作,目标是 JDK 9.

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

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

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