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

目录
  • 判断Integer类型的值是否相等
  • 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);
 }

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

(0)

相关推荐

  • Java修改Integer变量值遇到的问题及解决

    目录 Java 修改Integer变量值 下面我尝试了两种方法去改变Integer的整型值 看看源码 Integer值比较需要注意的问题 原因 解决办法 Java 修改Integer变量值 对于Integer变量来说,比较变量值常见情形如下: Integer a = 1000; Integer b = 1000; Integer c = 100; Integer d = 100; System.out.println(a == b); System.out.println(c == d); "=

  • 详谈java中int和Integer的区别及自动装箱和自动拆箱

    目录 int和Integer的区别及自动装箱和自动拆箱 Integer和int的对比,如下图所示: 自动装箱和自动拆箱: Integer的自动拆装箱的陷阱(整型数-128到127的值比较问题) 1.先看下面的例子: 2.以下是Integer.valueof()的源代码: int和Integer的区别及自动装箱和自动拆箱 1.Integer是int的包装类,int则是java的一种基本数据类型. 2.Integer变量必须实例化后才能使用,int则不需要. 3.Integer实际是对象的引用,当n

  • JAVA基本类型包装类 BigDecimal BigInteger 的使用

    目录 1.了解包装类 2.Integer 3.Double 4.BigDecimal 5.BigInteger 1.了解包装类 Java 中预定义了八种基本数据类型,包括:byte,int,long,double,float,boolean,char,short.基本类型与对象类型最大的不同点在于,基本类型基于数值,对象类型基于引用. 例如有一个方法 f() ,它的参数分别是对象类型 和 基本类型: void f(Object obj){ //参数引用类型,保存的是内存地址 } f(123){

  • 聊聊Java BigInteger里面的mod和remainder的区别

    目录 BigInteger里的mod和remainder区别 mod是模运算,remainder是求余运算 BigInteger类的一些使用心得 下面总结一下以后方便找 1.给大数赋值 2.把int型转化为string型 3.把两个字符串拼接 BigInteger里的mod和remainder区别 下面直接上图吧,稍后解释关于mod和remainder以及负数求余求模的区别. mod是模运算,remainder是求余运算 如果被除数是正整数,mod和remainder的结果没区别.mod运算除数

  • Java 处理超大数类型之BigInteger案例详解

    一.BigInteger介绍 如果在操作的时候一个整型数据已经超过了整数的最大类型长度 long 的话,则此数据就无法装入,所以,此时要使用 BigInteger 类进行操作.这些大数都会以字符串的形式传入. BigInteger 相比 Integer 的确可以用 big 来形容.它是用于科学计算,Integer 只能容纳一个 int,所以,最大值也就是 2 的 31 次访减去 1,十进制为 2147483647.但是,如果需要计算更大的数,31 位显然是不够用的,那么,此时 BigIntege

  • Java Integer对象的比较方式

    目录 Java Integer对象的比较 自动装箱 自动拆箱 Integer初始化 Integer对象之间的比较 Integer类型变量比较问题 代码1 代码2 代码3 代码4 关于这种现象,查了下资料,总结如下 Java Integer对象的比较 Integer对象之间的比较要考虑到对象初始化的不同情况,初始化又涉及到对象包装器类的自动装箱特性 . 自动装箱 Integer是一种对象包装器类.对象包装器类是不可变的,也就是说,一旦完成了构造,包装在其中的值就不可以再被更改了.包装器类有一种特性

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

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

  • mybatis参数String与Integer类型的判断方式

    目录 String与Integer类型的判断 我们一般是这样写 使用<if>标签判断Integer类型的坑 没想到还有另外的问题 注意上面的第二个条件使用的单个等号 String与Integer类型的判断 mybatis写update时,正常是set了值才会进行update操作 我们一般是这样写 <if test="sampleBatchNo != null and sampleBatchNo != ''"> SAMPLE_BATCH_NO =#{sampleB

  • Mybatis Integer类型参数值为0时得到为空的解决方法

    今日遇到的问题: 查询版本信息时,由于version是Integer类型,所以当前台选择版本为0时,变成了查询了所有的版本信息. sql片段: </if> <if test="version != null and version != '' "> AND a.version = #{version} </if> 原因: MyBatis因自身原因默认了 Integer类型数据值等于0时 为 ""(空字符串) 解决办法: 1. 某些

  • 详解Java中包装类Integer的使用

    一.Java中为什么引入包装类? 在Java中,很多类的方法都需要接受引用类型的对象,此时就无法将一个基本数据类型的值传入,为了解决这样的问题,JDK提供了一系列的包装类,通过这些包装类可以将基本数据类型的值包装为引用数据类型的对象 二.基本数据类型对应的包装类 在Java中,每种基本数据类型(共8种)都有对应的包装类,具体如下所示 除int.char外,其他包装类的名称和基本数据类型的名称一致,只是第一个字母大写即可 三.Integer 类和 int 的区别 ①Integer 是 int 包装

  • mybatis的坑-integer类型为0的数据if test失效问题

    integer类型为0的数据if test失效 mybatis的where动态判断语句if test 遇到tinyint类型为0的数据失效 发现一个mybatis的坑,有个支付表,通过状态去筛选已支付/未支付的数据,支付状态用status字段表示,status=0表示未支付,status=1表示已支付,且status类型为Integer.当选择已支付即status=1时,可以筛选成功已支付的数据列表,但是当选择未支付即status=0时,查出来的数据是未支付和已支付的所有数据. 此时就有点懵逼了

  • mybatis的if判断integer问题

    目录 if判断integer的问题 if判断integer类型注意点 if判断integer的问题 昨天在使用mybatis的if判断integer时遇见一个小问题: <if test="isChoose != null and isChoose != '' and isChoose == 0">      </if> 我发现前段同事调用接口的时候传参总是无法进入条件, 原来mybatis的if将0认为是'',所以这样判断是无法进入条件的,将数字换为1,2之类的

  • java两个integer数据判断相等用==还是equals

    目录 问题案例 原因分析 源码分析 解决方法 备注 问题案例 来个简单点的例子 public static void main(String[] args) { for (int i = 0; i < 150; i++) { Integer a = i; Integer b = i; System.out.println(i + " " + (a == b)); } } i取值从0到150,每次循环a与b的数值均相等,输出a == b.运行结果: 0 true 1 true 2

  • Java实现判断浏览器版本与类型简单代码示例

    简单的Java获取浏览器版本和类型方法,不是很完美,但是可以用: 希望大家加以完善! public static void main(String[] args) { String agent=request.getHeader("User-Agent").toLowerCase(); System.out.println(agent); System.out.println("浏览器版本:"+getBrowserName(agent)); } public Str

  • Java判断List中相同值元素的个数实例

    如下所示: Map<Object, Integer> map = new TreeMap<Object, Integer>(); for (Object i : listIp) { if (map.get(i) == null) { map.put(i, 1); } else { map.put(i, map.get(i) + 1); } } 以上这篇Java判断List中相同值元素的个数实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们.

  • Java形参和实参的实例之Integer类型与Int类型用法说明

    经常会有这样一道面试题,有两个整形变量分别是a = 1 ,b = 2.编写一个方法swap互换他们的值. 
class
 
Main
 
{


 
public
 
static
 
void
 main
(
String
[]
 args
)
 
{


 
Integer
 a 
=
 
1
;


 
Integer
 b 
=
 
2
;


 
System
.
out
.
println
(
"a="
 
+
 a 
+
 
",b="
 
+
 b


随机推荐