java 比较大小_你知道Java中数字怎么比较大小吗?

Java中除了对象这种引用类型,还有值类型。Java为了性能还有一种称为常量池的内存结构,这种用法就是设计模式中的享元模式因为常量池的出现,一些很容易理解的问题,变得复杂了本文就来理一理Java中Integer中如何比较大小呢?

先看个与预期一致的。Show the code.Code:package chapter4;/*** Created by MyWorld on 2016/3/19.*/public class IntegerEqalsVerify {   public static void main(String[] args) {       Integer source = 127;       Integer target = 127;       boolean result = source == target;       System.out.println("scene 1:" + result);       boolean resultForEquals = source.equals(target);       System.out.println("scene 2:" + resultForEquals);   }}

56dd74ef346265c47153cdd1d59ff083.png

执行上面的代码。都是true。这与我们的认知是一致的Output:scene 1:truescene 2:true

3394c7688df7045c19cb5f7827c9691b.png

把数字大小调整下,都改为128呢?Code:Integer source = 128;Integer target = 128;boolean result = source == target;

514c4219231e9a4b1e87c5b7e64fb331.png

执行下,看看结果:scene 1:falsescene 2:true傻眼了吧。为什么是false呢?

19ee227db49c562743d2cbb6055e81e6.png

只要是比127大的数字。在上面的场景中,执行结果都是一样的现在就来测个下限,先用数字-128.执行一下。可以看到,和平时的认知是一个的,都是trueCode:Integer source = -128;Integer target = -128;boolean result = source == target;

afe2420170aba972ecaba50a65c85b25.png

改成-129。看看执行结果:使用==比较时又不相等了。。。scene 1:falsescene 2:trueCode:Integer source = -129;Integer target = -129;boolean result = source == target;

d58860254ab8064b396f2a15c3cddc91.png

为什么呢?原因就出现在常量池了。如果Integer的值在[-128,127]时,都会从常量池中取。这样所有这个区间的Integer的对象是完全相同的,使用==比较肯定是true,因为内存地址是一样的的嘛过了这个区间的,肯定不同了,不同的对象,内存地址不一样了的。这种情况下,只能使用Equals来比较。对象之间比较是否相等,一定要使用Equals来一块看看java.lang.Integer.IntegerCacheprivate static class IntegerCache {   static final int high;   static final Integer cache[];   static {       final int low = -128;       // high value may be configured by property       int h = 127;       if (integerCacheHighPropValue != null) {           // Use Long.decode here to avoid invoking methods that           // require Integer's autoboxing cache to be initialized           int i = Long.decode(integerCacheHighPropValue).intValue();           i = Math.max(i, 127);           // Maximum array size is Integer.MAX_VALUE           h = Math.min(i, Integer.MAX_VALUE - -low);       }       high = h;       cache = new Integer[(high - low) + 1];       int j = low;       for(int k = 0; k < cache.length; k++)           cache[k] = new Integer(j++);   }   private IntegerCache() {}}

89fc71c03e19757aa6ba1154f3205bb1.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值