Java 如何判断Integer类型的值是否相等

 更新时间:2021年09月18日 11:02:51   作者:ryelqy  
这篇文章主要介绍了Java 如何判断Integer类型的值是否相等操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

判断Integer类型的值是否相等

我们知道Integer是int的包装类,在jdk1.5以上,可以实现自动装箱拆箱,就是jdk里面会自动帮我们转换,不需要我们手动去强转,所以我们经常在这两种类型中随意写,平时也没什么注意 但Integer他是对象,我们知道 == 比较的是堆中的地址,但有个奇怪的事是, 如果 Integer a = 123, Integer b = 123,可以返回true,但如果Integer a = 12345, Integer b = 12345,返回false

public class Demo { 
    public static void main(String[] args) {
        Integer c = -128;
        Integer d = -128;
        System.out.println("c == d: " + (c == d));
        System.out.println("c.equals(d): " + c.equals(d));
        System.out.println("c.intValue() == d.intValue(): " + (c.intValue() == d.intValue()));
        System.out.println("Objects.equals(c, d): " + Objects.equals(c, d));
        
        Integer e = 127;
        Integer f = 127;
        System.out.println("e == f: " + (e == f));
        System.out.println("e.equals(f): " + e.equals(f));
        System.out.println("e.intValue() == f.intValue(): " + (e.intValue() == f.intValue()));
        System.out.println("Objects.equals(e, f): " + Objects.equals(e, f));
        
        Integer g = 128;
        Integer h = 128;
        System.out.println("g == h: " + (g == h));
        System.out.println("g.equals(h): " + g.equals(h));
        System.out.println("g.intValue() == h.intValue():" + (g.intValue() == h.intValue()));
        System.out.println("Objects.equals(g, h): " + Objects.equals(g, h));
    }
}

结果如下:

c == d: true
c.equals(d): true
c.intValue() == d.intValue(): true
Objects.equals(c, d): true
e == f: true
e.equals(f): true
e.intValue() == f.intValue(): true
Objects.equals(e, f): true
g == h: false
g.equals(h): true
g.intValue() == h.intValue():true
Objects.equals(g, h): true

(1)当用“==”进行比较时,jvm默认是比较数据在java堆的地址。int是一种基本数据类型,jvm会自动将Integer转成int数值进行比较。在Integer类中,有一个内部静态类IntegerCache ,用来支持自动拆箱和装箱,如下,数值范围[-128,127]

/**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the -XX:AutoBoxCacheMax=<size> option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */
 
    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[]; 
        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                int i = parseInt(integerCacheHighPropValue);
                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() {}
    }

默认IntegerCache.low 是-127,Integer.high是128,如果在这个区间[-128,127]内,他就会把变量i当做一个变量,放到内存中,用“==”比较是会得出true;但如果不在这个范围内,就会去new一个Integer对象,当运用“==”时,会比较Integer两个对象地址,得出false。

比较两个Integer的值是否相同,方法比较多:

1、推荐用equals(),这个还可以避免一些空指针问题的出现。

2、或者使用Integer.intValue();这样出来的就是int值,就可以直接比较了(可能会抛出空指针异常);

Integer赋值比较

Integer是int的包装类,继承Number类另实现Comparable接口,其取值范围为:-2147483648~2147483647

赋值操作

 Integer newInt = new Integer(10);
 //自动装箱操作,编译后class文件中为:Integer num = Integer.valueOf(10);
 Integer num = 10;
 //num.intValue()为解包操作
 int intNum = num.intValue();
 /**
  * 输出结果为true----false----true,原因:
  * 1、 Integer为引用类型,引用类型栈中变量表示一个地址指向堆中的一片内存空间
  * 2、 newInt.equals(num)为true是因为Integer重写了equals方法,equals方法中实际是值比较
  * 3、(newInt == num)为false因为两个变量不指向同一片内存
  * 4、(intNum==num)结果为true是因为intNum是基本数据类型,值直接存在栈中,两者比较的是值
  */
 System.out.println(newInt.equals(num)+"----"+(newInt == num)+"----"+(intNum==num));
    private final int value;
    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
         //将对象强制转换为Integer类型,然后自动拆箱进行==比较
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

构造函数

 public Integer(int value) {
  //参数为int 直接赋值
  this.value = value;
 }
 public Integer(String s) throws NumberFormatException {
  //参数为String的情况下调用paseInt()方法进行赋值,10表示为按10进制转换
  this.value = parseInt(s, 10);
 }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java基于Swing和netty实现仿QQ界面聊天小项目

    Java基于Swing和netty实现仿QQ界面聊天小项目

    这篇文章主要为大家详细介绍了Java如何利用Swing和netty实现仿QQ界面聊天小项目,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下
    2022-09-09
  • Spring Security基于过滤器实现图形验证码功能

    Spring Security基于过滤器实现图形验证码功能

    验证码就是为了防止恶意用户采用暴力重试的攻击手段而设置的一种防护措施,接下来在Spring Security的环境中,我们可以用两种方案实现图形验证码,具体实现方法跟随小编一起看看吧
    2021-09-09
  • Mybatis代码生成器Mybatis Generator(MBG)实战详解

    Mybatis代码生成器Mybatis Generator(MBG)实战详解

    本文我们主要实战Mybatis官方的代码生成器:Mybatis Generator(MBG),掌握它以后,可以简化大部分手写代码,我们只需要写复杂逻辑代码,需要的朋友可以参考下
    2023-05-05
  • java转换字符串编码格式的方法

    java转换字符串编码格式的方法

    这篇文章主要介绍了java转换字符串编码格式的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-08-08
  • 深度解析SpringBoot中@Async引起的循环依赖

    深度解析SpringBoot中@Async引起的循环依赖

    本文主要介绍了深度解析SpringBoot中@Async引起的循环依赖,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-02-02
  • java多线程之火车售票系统模拟实例

    java多线程之火车售票系统模拟实例

    下面小编就为大家带来一篇java多线程之火车售票系统模拟实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-06-06
  • springboot Quartz动态修改cron表达式的方法

    springboot Quartz动态修改cron表达式的方法

    这篇文章主要介绍了springboot Quartz动态修改cron表达式的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-09-09
  • Java模版引擎Freemarker

    Java模版引擎Freemarker

    FreeMarker是一个模板引擎,一个基于模板生成文本输出的通用工具,使用纯Java编写 FreeMarker被设计用来生成HTML Web页面,特别是基于MVC模式的应用程序
    2016-04-04
  • intellij idea查看方法被哪些类引用过(推荐)

    intellij idea查看方法被哪些类引用过(推荐)

    这篇文章主要介绍了intellij idea查看方法被哪些类引用过,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-08-08
  • SpringMVC后端Controller页面跳转的三种方式汇总

    SpringMVC后端Controller页面跳转的三种方式汇总

    这篇文章主要介绍了SpringMVC后端Controller页面跳转的三种方式汇总,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-10-10

最新评论