Java的自动装箱和自动卸载
来源:互联网 发布:手机淘宝优惠券链接 编辑:程序博客网 时间:2024/05/03 17:29
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概念
2).代码编译通过,运行时候抛出空指针异常,主要在自动拆箱对象中null,基本数据类型没有null概念
所以自动拆箱时候注意 不能有 null 对象
Integer integer100=null;int int100=integer100;运行结果 Java.lang.nullPointError()异常
3).Integer 自动装箱时候 注意-128~127 相同的地址引用,超过这个范围之后 开辟新的对象
运行结果 true false
0 0
- Java的自动装箱和自动卸载
- java---自动装箱和自动取消装箱
- Java的自动装箱
- JavA的自动装箱和拆箱
- Java的自动拆箱和装箱
- java的自动装箱和拆箱
- Java自动装箱和自动拆箱的陷阱
- java的自动装箱和自动拆箱
- Java 自动装箱和自动拆箱注意的问题
- Java的自动装箱和自动拆箱
- java 自动装箱 和 自动拆箱
- java自动装箱和自动拆箱
- Java自动拆箱和自动装箱
- Java自动装箱和自动拆箱
- JAVA自动装箱和自动拆箱
- Java自动装箱和自动拆箱
- Java自动装箱和自动拆箱
- java的自动装箱自动拆箱
- Netty5.0使用简单介绍
- CentOS7搭建Docker私有仓库
- 获取MySQL配置文件路径
- 网站站长如何做好网站的搜索引擎优化
- **UE4 插件编译及使用的问题**
- Java的自动装箱和自动卸载
- Android 本地广播LocalBroadcastManager原理分析
- Linux驱动概念扫盲篇
- js判断ie游览器
- Spring注解@Component、@Repository、@Service、@Controller区别
- 数组(一)
- 使用lame转换音频时遇到的杂音问题
- MYSQLI连接数据库
- 了解spring