Java-convert between INT and STRING

int -> String

三种写法

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

分析

  1. String s = 43 + "";
    实际上进行了如下操作:a)初始化一个StringBuilder; b)append一个43; c)append一个空字符串; d)将此sb toString()
  2. String s = String.valueOf(43);
    内部实现调用了3,但3有类型校验,建议使用3
  3. String 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

两种写法

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

分析

  1. int i = Integer.parseInt("43");
    返回int
  2. Integer 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