1、前言:Java是典型的面向对象编程语言,但其中有8种基本数据类型不支持面向对象编程,基本数据类型不具备对象的特性,没有属性和方法;Java为此8种基本数据类型设计了对应的类(包装类),使之相互转换,间接实现基本数据类型具备对象特性,丰富基本数据类型操作;

基本数据类型 包装类
byte Byte
short Short
int Integer
long Long
char Character
float Float
double Double
boolean Boolean  

  

注:int是基本数量类型,Integer是类;int和Ingeger初始值不同(int默认值0 Ingeger默认值null);Integer包含属性和方法,int则没有;基本数据类型和包装类相互转换的过程叫装箱和拆箱;

2、装箱:基本数据类型转换成对应的包装类(int——>Integer);

Integer i = new Integer(); // 手动装箱
Integer i = ; // 自动装箱

3、拆箱:包装类转换成基本数据类型(Integer——>int);

Integer i = Integer.valueOf(); // 调用valueOf方法自动装箱
 int n = i.intValue(); // 调用intValue方法自动拆箱
 

注:自动装箱会隐式地创建对象,在一个循环中注意自动装箱问题,影响程序性能;

5、equals 和 == 比较:当 "=="运算符的两个操作数都是包装类,则是比较指向的是否是同一个对象,而如果其中有一个操作数是表达式(即包含算术运算)则比较的是数值(触发自动拆箱);对于包装类,equals方法不会进行类型转换;

public class Main {
public static void main(String[] args) { Integer a = ;
Integer b = ;
Integer c = ;
Integer d = ;
Integer e = ;
Integer f = ;
Long g = 3L;
Long h = 2L; System.out.println(c==d); // true
System.out.println(e==f); // false
System.out.println(c==(a+b)); // true
System.out.println(c.equals(a+b)); // true
System.out.println(g==(a+b)); // true
System.out.println(g.equals(a+b)); // false
System.out.println(g.equals(a+h)); // true
}
}

解析:JVM会缓存-128到127的Integer对象(Short、Byte、Character、Long与Integer类似),所以第一个是同一个对象true,第二个是new的新对象false;第三个有+法运算比较的是两边的值true;第四个有+法运算且两边的数据类型相同true;第五个同四先求+法求和 ,==会进行类型转换(Long)true;第六个先+法求和,equals不会类型转换false;第七个先+法求和(触发拆箱,变成了int类型和long类型相加,这个会触发类型晋升,结果是long类型的)equals比较时触发装箱比较两边都是Long类型结果true;

最新文章

  1. 使用视 meta 标签来控制手机浏览器布局
  2. GDUFE-OJ 1361校庆抽奖 翻转
  3. 【转】java中volatile关键字的含义
  4. 【Codeforces 722C】Destroying Array (数据结构、set)
  5. Intersection of Two Linked Lists | LeetCode
  6. Object-c : block需要注意的几点问题
  7. 将商户后台_门店管理后台_平台后台管理v1.0 Axure RP项目上传到svn服务器步骤
  8. 1. 走进java
  9. SQLite数据库的加密【转】
  10. C# 中使用 OpenSSL 的公钥/私钥进行加密和解密
  11. Powershell环境变量
  12. Extjs视频
  13. Cocos2D:塔防游戏制作之旅(十)
  14. Charles SSL
  15. (办公)mysql连接不上(java.sql.SQLException: null, message from server: "Host 'LAPTOP-O0GA2P8J' is not allowed to connect to this MySQL server")(转)
  16. vue跳坑笔记
  17. Tgrocery学习及使用
  18. Introduction to MyBatis Generator Mybatis代码生成介绍
  19. mac python2.7.10 升级到 3.6
  20. git连接报错:Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password)

热门文章

  1. 解析URL中的携带的参数到Map
  2. 连接到 Linux 服务器时首先要运行的 5 个命令
  3. cocos2dx 3.3 异步加载纹理
  4. unity, Rigidbody.constraints
  5. HttpOperater
  6. zeroclipboard解决跨域问题
  7. ubuntu下将CapsLock改为Ctrl键
  8. 2、visual studio 常用设置
  9. python用time函数计算程序运行时间
  10. 基于HTML5坦克大战游戏简化版