美文网首页
Java 包装类的自动拆装箱与相等判断

Java 包装类的自动拆装箱与相等判断

作者: 一片彬心在玉壶 | 来源:发表于2018-05-06 07:25 被阅读15次
缘起:

基本类型的包装类的使用中经常会遇到自动拆箱和自动装箱,有时候会因为操作不规范导致一些意想不到的问题。

注意

在使用包装类的时候要注意一下事项

  1. 用基本类型来赋值给包装类的时候,会有自动装箱
    调用相关包装类的valueOf方法。

    [附一,自动装箱代码反编译]

  1. 判断是否相等时使用equal时,会自动拆箱,使用基本值 == 判断。

  2. 尽量不要使用 == 判断,需要注意以下情况:

    1. 包装类会有相应的基本类的缓存数组,一般范围是在-128 - 127,如果有的话会返回缓存的对象。
    2. 范围外的都是新建的对象。
    3. 不包含Float、Double

以下Byte的相关源码


Byte
    //自动装箱,调用内部类缓存
    public static Byte valueOf(byte b) {
        final int offset = 128;
        return ByteCache.cache[(int)b + offset];
    }
    
    // 静态内部类,包含相应包装类数组,已事先创建好对象
    private static class ByteCache {
        private ByteCache(){}

        static final Byte cache[] = new Byte[-(-128) + 127 + 1];

        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Byte((byte)(i - 128));
        }
    }
    
    //equal对比,如果是包装类,就使用基本类相等
    public boolean equals(Object obj) {
        if (obj instanceof Byte) {
            return value == ((Byte)obj).byteValue();
        }
        return false;
    }
   

其他包装类类似。
[附二,相应包装类的JDK 源码]

不包括 Float、Double


附一,自动装箱代码反编译
使用javap -c 命令查看相应代码的反编译指令
    public void testEqual() {
        Integer i1 = 1;
        Integer i2 = 1;
        System.out.println(i1 == i2);
    }

javap -c 相应字节码,得出以下反编译结果

    public void testEqual();
    Code:
       0: iconst_1  // int类型 1 入操作数栈
       1: invokestatic  #2                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;  自动装箱
       4: astore_1  // 栈顶元素赋值 位置1变量
       5: iconst_1  // int 1 入栈
       6: invokestatic  #2                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
       9: astore_2  // 栈顶元素赋值 给位置2变量
      10: getstatic     #3                  // Field java/lang/System.out:Ljava/io/PrintStream;
      13: aload_1  //从位置为1的局部变量中取出元素int类型的1压入栈
      14: aload_2  //从位置为2的局部变量中取出元素int类型的1压入栈
      15: if_acmpne     22
      18: iconst_1
      19: goto          23
      22: iconst_0
      23: invokevirtual #4                  // Method java/io/PrintStream.println:(Z)V

其他包装类的JDK 源码
    
//Character
    public static Character valueOf(char c) {
        if (c <= 127) { // must cache
            return CharacterCache.cache[(int)c];
        }
        return new Character(c);
    }
    
    
    private static class CharacterCache {
        private CharacterCache(){}

        static final Character cache[] = new Character[127 + 1];

        static {
            for (int i = 0; i < cache.length; i++)
                cache[i] = new Character((char)i);
        }
    }
    
    public boolean equals(Object obj) {
        if (obj instanceof Character) {
            return value == ((Character)obj).charValue();
        }
        return false;
    }
    
//Short

    public static Short valueOf(short s) {
        final int offset = 128;
        int sAsInt = s;
        if (sAsInt >= -128 && sAsInt <= 127) { // must cache
            return ShortCache.cache[sAsInt + offset];
        }
        return new Short(s);
    }
    
     private static class ShortCache {
        private ShortCache(){}

        static final Short cache[] = new Short[-(-128) + 127 + 1];

        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Short((short)(i - 128));
        }
    }

    
    public boolean equals(Object obj) {
        if (obj instanceof Short) {
            return value == ((Short)obj).shortValue();
        }
        return false;
    }
    
    //Integer
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
    
    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }
    
    
    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }
    
    //Long
    public static Long valueOf(long l) {
        final int offset = 128;
        if (l >= -128 && l <= 127) { // will cache
            return LongCache.cache[(int)l + offset];
        }
        return new Long(l);
    }
    
    private static class LongCache {
        private LongCache(){}

        static final Long cache[] = new Long[-(-128) + 127 + 1];

        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Long(i - 128);
        }
    }
    
    
    public boolean equals(Object obj) {
        if (obj instanceof Long) {
            return value == ((Long)obj).longValue();
        }
        return false;
    }

相关文章

  • 三 常用API第二部分——第六节 包装类

    1、包装类的概念 2、装箱与拆箱 装箱:基本类型-->包装类对象拆箱:包装类对象-->基本类型 3、自动装箱与拆箱...

  • Java 包装类的自动拆装箱与相等判断

    缘起: 基本类型的包装类的使用中经常会遇到自动拆箱和自动装箱,有时候会因为操作不规范导致一些意想不到的问题。 注意...

  • Java基础—杂记

    1.自动装箱与自动拆箱 对于常用的基本数据类型,Java都有对应的Java包装类,Java提供了基本数据类型与...

  • 8.包装类,包装类的自动装箱和自动拆箱

    问题:关于 Java 包装类,包装类的自动装箱和自动拆箱你怎么理解? 从程序语言来说,Java语言是一个面向对象语...

  • Java--自动装箱和拆箱

      自动装箱和拆箱就是将基本数据类型和包装类之间进行自动的互相转换。JDK1. 5后,Java引入了自动装箱(au...

  • java中的自动装箱和拆箱机制

    java中的自动装箱和拆箱机制 概念 自动装箱:将基本数据类型转换为包装器类型 自动拆箱:将包装器类型转换为基本数...

  • 从0开始复习java(3)

    一、面向对象 1、包装类 java5之后有自动装箱和自动拆箱功能。 包装类可以实现基本类型变量和字符串之间的转换。...

  • 6、java自动装箱与拆箱

    java自动装箱与拆箱 装箱就是自动将基本数据类型转换为包装器类型(int->Integer);调用方法:Inte...

  • (Note) Java-autoBoxing-unBoxing

    0. Thanks Java中的自动装箱与拆箱 Java 自动装箱与拆箱的实现原理 Integer.java 1....

  • Java的自动拆装箱-学习笔记

    装箱与拆箱 装箱:Java为每种基本数据类型都提供了对应的包装器类型,从Java SE5开始就提供了自动装箱的特性...

网友评论

      本文标题:Java 包装类的自动拆装箱与相等判断

      本文链接:https://www.haomeiwen.com/subject/yyuyrftx.html