string转int,两种方法:
1、Interger.parseInt(String)
2、Interger.valueOf(String).intValue()
第二种方法可以去看源码,实现了第一种方法。

注释大概就是这样的意思
* {@code new Integer(Integer.parseInt(s))}
*
*
* @param是要解析的字符串。
* @返回一个保存值的{整数}对象
*由字符串参数表示。
* @exception NumberFormatException如果字符串不能被解析
*作为一个整数。
*/
在valueOf()里面实现了parseInt()方法。时间对比第二种比第一种要快了很多。
Integer.parseInt(str) : 21
Integer.valueOf(str).intValue() : 14
——————————————————————————–
int 转string一般用三种方法:
第一种:number + “”
第二种:string.valueOf()
第三种:.toString()
先说第一种,简单粗暴。
第二种方法:底层使用的依旧是.toString()方法
第三种就是toString()
上代码。
int num = ; //(1)num + "" long start = System.currentTimeMillis();//得到开始运行时系统时间 for(int i=0; i<; i++){ String str = num + ""; } long end = System.currentTimeMillis();//得到结束运行时系统时间 System.out.println("num + \"\" : " + (end - start)); //(2)String.valueOf(num) start = System.currentTimeMillis(); for(int i=0; i<; i++){ String str = String.valueOf(num); } end = System.currentTimeMillis(); System.out.println("String.valueOf(num) : " + (end - start)); //(3)Integer.toString(num) start = System.currentTimeMillis(); for(int i=0; i<; i++){ String str = Integer.toString(num); } end = System.currentTimeMillis(); System.out.println("Integer.toString(num) : " + (end - start));
结果就是
经过多次的反复测试,toString()是最快的,num+""是最慢的,在使用String.valueOf()中源码是这样的。
public static String valueOf(Object obj) { return (obj == null) ? "null" : obj.toString(); }
也就是说在使用的时候,不用去判断所传的对象是否为null,但是尤其注意,如果传的为空,返回来的是一个为null的字符串而不是null值,这个地方需要谨记。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/177608.html原文链接:https://javaforall.net
