Java的自动装箱和自动卸载

xiaoxiao2021-02-28  175

1.Java自动装箱和拆箱

     ⒈什么是自动装箱:对于基本数据类型int,double和char 不是对象类型,有时候处理是对象型的数据因此将int、double和char 自动装箱成包装类Integer,Double和Character。 类如:对于自动装箱编译器自动调用:Integer i=Integer.valueOf(100);通过自动装箱将基本数据转化成对象 对如下程序进行断点测试: Integer i=100;发现程序自动的调转到Integer类的valueOf() 的方法: 从源代码看出 对于-128~127 相同对象引用,超出127 Integer 建立新的对象 equals() :方法比较两个对象中值,==比较两个对象引用地址 /** * Returns a <tt>Integer</tt> instance representing the specified * <tt>int</tt> value. * If a new <tt>Integer</tt> 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. * * @param i an <code>int</code> value. * @return a <tt>Integer</tt> instance representing <tt>i</tt>. * @since 1.5 */ public static Integer valueOf(int i) { if(i >= -128 && i <= IntegerCache.high) return IntegerCache.cache[i + 128]; else return new Integer(i); } 2.自动拆箱:将对象中基本数据从对象中取出来: 实质 :调用对象的intValue();方法 同理: Integer integer100=100; int int100=integer100; 进行断点测试发现确实调用的是intValue()方法 /** * Returns the value of this <code>Integer</code> as an * <code>int</code>. */ public int intValue() { return value; } 3.总结:      1).查看下面是属于自动装箱还是自动拆箱:对象==基本数据类型  进行自动拆箱操作 当两个对象进行比较==比较相同的地址引用 public static void main(String[] args) { Integer integer100=100; int int100=100; System.out.println(integer100==int100); } 运行结果是 true:  原因:如果是自动装箱的话 那么==比较两个实例的引用地址,明显出现false,但是运行结果True,表明对象数据类型与基本数据类型进行 比较对象进行自动拆箱操作    2).代码编译通过,运行时候抛出空指针异常,主要在自动拆箱对象中null,基本数据类型没有null概念 所以自动拆箱时候注意 不能有 null 对象      Integer integer100=null; int int100=integer100;  运行结果 Java.lang.nullPointError()异常 3).Integer 自动装箱时候 注意-128~127 相同的地址引用,超过这个范围之后 开辟新的对象   运行结果 true false
转载请注明原文地址: https://www.6miu.com/read-18431.html

最新回复(0)