java - parseInt和valueOf的区别?
ringa_lee
ringa_lee 2017-04-17 17:59:04
0
3
477

public class IntegerDemo4 {

public static void main(String[] args) { String str = "123"; int i = Integer.parseInt(str);

// int i = Integer.valueOf(str);

//parseInt和valueOf在这里用结果都对,但区别是什么呢?谢谢大家解答一下^_^

System.out.println(i+1); double d = Double.parseDouble(str); System.out.println(d+1); }

}

ringa_lee
ringa_lee

ringa_lee

reply all (3)
Peter_Zhu

valueOf内部就用了parseInt,区别在于parseInt直接返回原始int类型数据;而valueOf又装了下箱,返回IntegerType.

There is another difference,parseInt期待输入是String,而valueOfis not

Feel the code:

public static int parseInt(String s) throws NumberFormatException { return parseInt(s,10); } public static Integer valueOf(String s, int radix) throws NumberFormatException { return Integer.valueOf(parseInt(s,radix)); } public static Integer valueOf(String s) throws NumberFormatException { return Integer.valueOf(parseInt(s, 10)); }
    Ty80

    See source code:

    //先调用parseInt获得int值,然后封装成Integer对象,注意封装的逻辑,有缓存 public static Integer valueOf(String s) throws NumberFormatException { return Integer.valueOf(parseInt(s, 10)); } public static Integer valueOf(int i) { assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); } //直接转换,获得int值 public static int parseInt(String s) throws NumberFormatException { return parseInt(s,10); }

    In summary, generally use theInteger.parseInt(str),除非你要返回Integertype, otherwise there will be packaging and unboxing, which will consume some performance.

      Peter_Zhu

      parseint returns int directly. valueof will do the encapsulation

        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!