用java进行强制转换的更好方法是什么

用java进行强制转换的更好方法是什么,java,type-conversion,Java,Type Conversion,在我编写代码的各个地方,我需要将整数值更改为字符串值。要将强制转换整数转换为字符串,我使用带“”的串联转换为整数 我发现另一种方法是使用String.parseInt(…)方法 我的问题是,我不知道在java中哪种方法是优化的,它是如何优化的?。除了我的代码,还有其他方法可以强制转换吗 我的示例代码: int total = mark1 + mark2; String str_total = ""+total; // currently doing. String str_total =

在我编写代码的各个地方,我需要将整数值更改为字符串值。要将强制转换整数转换为字符串,我使用带“”的串联转换为整数

我发现另一种方法是使用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); 

在代码中使用整数rahter than int,然后在整数上使用toString()

Integer total = mark1 + mark2;
String str_total = total.toString();
在代码中-

字符串str_total=“”+总计

实际上,您正在创建两个新的字符串对象,第一个是
,第二个是
str\u total

但是在我的代码中,只会创建一个新的字符串对象

字符串类中valueOf的实现如下所示-

   public static String valueOf(int i) {
        return Integer.toString(i);
    }
这里toString将创建一个新的String对象

String str_total = String.valueOf(total); 
String.valueOf(int)
“”+int
更有效,因此更喜欢使用
String.valueOf(int)

请参阅性能中的测量链接

在Jdk>1.5中,您也可以使用它

String str_total= String.format ("%d", total);

另一种方法是:

int intValue = 1;    
String str1 = String.format("%d", intValue);
您还可以控制值的显示方式(前导零、基等)。查找更多信息

最酷的是,在我看来

String str2 = String.format("Blabla %d blupp %dm etc", intValue1, intValue2);
看起来更可读(如果您熟悉格式),然后

(+您可以更好地控制它的显示方式。

String.valueOf(int)方法调用
Integer.toString(int)

执行字符串连接(
“”+i
),首先将
i
转换为
整数
,然后调用函数
整数。调用toString
以获取整数的
字符串


因此,调用
String.valueOf(int)
将比字符串连接执行得更好,因为它跳过了
Integer
对象的创建。

因为
Integer
不能容纳如此大的值,这将导致它用科学符号表示,我认为

Integer.toString()
完全有效

如果您想以某种方式格式化您的号码,您应该像这样使用
NumberFormat

Integer myInt = 31535468;
NumberFormat nf = NumberFormat.getInstance();
String myString = nf.format(myInt);

我认为使用
NumberFormat
是这里最常用的方法。

有两个问题要问你;1) 你打算做多少次这个手术?(换句话说,你能证明优化的必要性吗?)字符串中没有parseInt方法。你的意思可能是valueOf。我需要性能方面的良好编码,以便进行优化。如果只使用几次(而不是至少使用几千次),代码可读性比性能更重要,因为你不会从中赢得超过几微秒的时间…小心过早优化的危险,尤其是微优化。请解释代码是如何比我的代码优化的?我指的是快速运行和内存/对象利用率。感谢您的回答,我选择了String.valueOf(int)。感谢您的回答和解释。我选择String.valueOf(int)。
Integer myInt = 31535468;
NumberFormat nf = NumberFormat.getInstance();
String myString = nf.format(myInt);