隐式转换为字符串toString和int +“” [英] Implicit cast to string - toString and int + ""

查看:168
本文介绍了隐式转换为字符串toString和int +“”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么当我使用这个:

int a = 1;
methodWithParamString(a + "");

a被转换为String,bu不能对整数使用toString >

a is cast to String, bu i can't use toString() on integer?

int a = 1;
methodWithParamString(a.toString());

不是这样: a +工作原理: a.toString()+

Doesn't this: a+"" works like: a.toString() + "" ?

推荐答案

不,它的工作原理是 String.valueOf(a)+,它的行为类似 new StringBuilder(String.valueOf(a)).append().toString()

No, it works like String.valueOf( a ) + "", which in turn behaves like new StringBuilder( String.valueOf( a ) ).append( "" ).toString().

重要的是要知道它是由编译器完成的,换句话说它是语法糖。这就是为什么在循环中添加字符串不是一个好主意。 (虽然现代虚拟机可能有一些机制来降低性能开销。)

The important thing to know is that it's all just done by the compiler, in other words it's syntactic sugar. This is why adding strings together in a loop isn't a good idea for example. (Although modern VMs might have some mechanism to reduce the performance overhead.)

这篇关于隐式转换为字符串toString和int +“”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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