java中int和integer比较,integer和integer比较

来源:互联网 发布:windows优化大师64 编辑:程序博客网 时间:2024/06/11 03:51

先看一代代码:

public static void main(String[] args) {long test = 012;float f = -412;double d = 0x12345678;Integer io1 = 59;int io2 = 59;Integer io3 = Integer.valueOf(59);Integer io4 = new Integer(59);Integer io5 = new Integer(59);System.out.println(io1 == io2);System.out.println(io1 == io3);System.out.println(io1 == io4);System.out.println(io1 == io5);System.out.println(io2 == io3);System.out.println(io2 == io4);System.out.println(io2 == io5);System.out.println(io3 == io4);System.out.println(io3 == io5);System.out.println(io4 == io5);}



输出结果为:

true
true
false
false


true
true
true


false
false


false

先给出valueof的代码:

    /**     * Returns an {@code Integer} instance representing the specified     * {@code int} value.  If a new {@code Integer} instance is not     * required, this method should generally be used in preference to     * the constructor {@link #Integer(int)}, as this method is likely     * to yield significantly better space and time performance by     * caching frequently requested values.     *     * This method will always cache values in the range -128 to 127,     * inclusive, and may cache other values outside of this range.     *     * @param  i an {@code int} value.     * @return an {@code Integer} instance representing {@code i}.     * @since  1.5     */    public static Integer valueOf(int i) {        if (i >= IntegerCache.low && i <= IntegerCache.high)            return IntegerCache.cache[i + (-IntegerCache.low)];        return new Integer(i);    }

如上图代码,如面中,默认如果不new的话,会维持一个integer池,范围是-128~127

前4个,

所以io1是在integer池里面的,而valueof弄出的59,也是在同一个池子里面,所以io1和io3为true。

而io2与任何的比,都是讲integer转为int,所以只要数值相同,就相等。

io4和io5为新new出的,所以比较的是内存中地址,不相等,故io1和io4不等,io1和io5不等。

后面3个,

有分析知,io2与其他比较都相等。

后面2个,

io3在池子里面,而io4和io5都是新new出来的。

最后1个,

io4和io5是新new出来的,故不等















0 0
原创粉丝点击