Java-convert between INT and STRING

it2022-05-09  61

int -> String

三种写法

String s = 43 + "";String s = String.valueOf(43);String s = Integer.toString(43);

分析

String s = 43 + "";实际上进行了如下操作:a)初始化一个StringBuilder; b)append一个43; c)append一个空字符串; d)将此sb toString()String s = String.valueOf(43);内部实现调用了3,但3有类型校验,建议使用3String s = Integer.toString(43);只调用一个静态方法

总结

使用Integer.toString是最优的选择,就像原文所说的

It is not that one need to optimize everything to this level, but learning a few good habits like this will help in the long run.

String -> int/Integer

两种写法

int i = Integer.parseInt("43");Integer i = Integer.valueOf("43");

分析

int i = Integer.parseInt("43");返回intInteger i = Integer.valueOf("43");返回Integer

参考

http://stackoverflow.com/questions/14712693/best-practices-for-converting-from-int-to-string

http://stackoverflow.com/questions/4105331/how-to-convert-from-int-to-string

http://stackoverflow.com/questions/508665/difference-between-parseint-and-valueof-in-java 

转载于:https://www.cnblogs.com/maozhige/p/4226105.html


最新回复(0)