在我编码的各个地方,我需要将整数值更改为字符串值。要将强制转换的整数转换为字符串,我使用concatenation with ""to integer。
我找到了另一种使用 String.parseInt(..); 方法的方法。
我的问题是我不知道在 Java 中进行转换的优化方法是什么以及它是如何优化的?除了我的代码,还有其他转换方式吗?
我的示例代码:
int total = mark1 + mark2;
String str_total = ""+total; // currently doing.
.......
String str_total = String.parseInt(total); // i am planning to do.
最佳答案
你也可以使用 -
String str_total = String.valueOf(total);
或
在您的代码中使用 Integer rahter 而不是 int,然后像这样在 Integer 上使用 toString()
Integer total = mark1 + mark2;
String str_total = total.toString();
在您的代码中-
String str_total = ""+ 总数;
实际上,您首先为 ""
创建了 2 个新的字符串对象,第二个为 str_total
但在我的代码中只会创建一个新的字符串对象
。
String类中valueOf的实现如下——
public static String valueOf(int i) {
return Integer.toString(i);
}
这里toString会创建一个新的String对象
关于java - 这是在 Java 中进行转换的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11427793/