Java基础之数据比较Integer、Short、int、short | 您所在的位置:网站首页 › float和int比较大小 › Java基础之数据比较Integer、Short、int、short |
基础很重要,基础很重要,基础很重要。重要的事情说三遍,。 今天聊一聊Java的数据比较,这个范围比较大,基础类型的比较、引用类型的比较。 前提: 1、Java和c#都提供自动装箱和自动拆箱操作,何为自动装箱,简单点说就是将值类型转换成为引用类型,自动拆箱就是将引用类型转换成为值类型。并且我们还经常被教导,要避免自动的装箱和拆箱操作,因为这个会影响性能。 2、比较常用的运算符是==,equals。 下面分几类来说明数据的比较, 引用类型之间的比较:Integer与Integer之间的比较、Boolean与Boolean之间的比较、Integer与Boolean之间的比较 值类型之间的比较:int与int之间的比较、int与bool之间的比较 值类型与引用类型之间的比较:Integer与int之间的比较、Boolean与bool之间的比较 开工 引用类型之间的比较--Integer与Integer之间的比较 简单说明一下,Integer是引用类型,代表的是整形数字 上代码 1 public static void main(String[] args) throws Exception { 2 Integer integer = new Integer(0); 3 Integer mInteger = Integer.valueOf(0); 4 Integer sInteger = 0; 5 6 System.out.println(integer == mInteger);//false 7 System.out.println(integer == sInteger);//false 8 System.out.println(mInteger == sInteger);//true 9 10 System.out.println(memoryAddress(integer)); 11 System.out.println(memoryAddress(mInteger)); 12 System.out.println(memoryAddress(sInteger)); 13 14 } 15 16 private static int memoryAddress(Object object) { 17 // 内存地址会有所不同 18 return System.identityHashCode(object); 19 }
执行结果: 分析: 1、执行结果和我们预想的不太一样,引用类型是在堆上存放的,每个引用的地址应该都不相同。但是mInteger == sInteger 执行结果为true,并且mInteger ,sInteger的内存地址是相同的。 2、要分析这个原因,我们需要了解Java设计者为了性能而进行的一些努力,查看Java源代码,可以看到Integer的valueof方法里面包含了一个缓存:其中IntegerCache.low =-127,IntegerCache.high=128 1 @HotSpotIntrinsicCandidate 2 public static Integer valueOf(int i) { 3 if (i >= IntegerCache.low && i |
CopyRight 2018-2019 实验室设备网 版权所有 |