int 和Integer

Java是一个近乎纯洁的面向对象编程语言,但是为了编程的方便还是引入不是对象的基本数据类型,但是为了能够将这些基本数据类型当成对象操作,Java为每一个基本数据类型都引入了对应的包装类型(wrapper class),int的包装类就是Integer,从JDK 1.5开始引入了自动装箱/拆箱机制,使得二者可以相互转换。

8种基本类型: boolean,char,byte,short,int,long,float,double

     包装类型:Boolean,Character,Byte,Short,Integer,Long,Float,Double

 1 package com.rong.test;
 2 
 3 public class TestClass {
 4     public static void main(String[] args) {
 5         int t1 = 3;
 6         Integer t2 = 3,t=3; // 将3自动装箱成Integer类型
 7         Integer t3 = new Integer(3);
 8         System.out.println(t1 == t2);// true t2自动拆箱成int类型再和t1比较
 9         System.out.println(t1 == t3);// true t3自动拆箱成int类型再和t1比较
10         System.out.println(t2 == t3);// false 两个引用没有引用同一对象
11         System.out.println(t==t2);//true
12         // //////////////自动装箱和拆箱////////////////////////////////////
13         System.out.println("######################################");
14         Integer f1 = 100, f2 = 100, f3 = 150, f4 = 150;
15 
16         System.out.println(f1 == f2);//true
17         System.out.println(f3 == f4);//false
18         
19         Integer x1=128,x2=128;
20         System.out.println(x1==x2);//false
21         Integer y1=127,y2=127;
22         System.out.println(y1==y2);//true
23 
24     }
25 
26 }

需要注意的是f1、f2、f3、f4四个变量都是Integer对象,所以下面的==运算比较的不是值而是引用。装箱的本质是什么呢?当我们给一个Integer对象赋一个int值的时候,会调用Integer类的静态方法valueOf,如果看看valueOf的源代码就知道发生了什么。

简单的说,如果字面量的值在-128到127之间,那么不会new新的Integer对象,而是直接引用常量池中的Integer对象,所以上面的f1==f2的结果是true,而f3==f4的结果是false。

原文地址:https://www.cnblogs.com/57rongjielong/p/8035559.html