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

您所在的位置:网站首页 javainteger比较大小用大于 Java判断Integer类型的值是否相等

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

2024-07-12 00:33| 来源: 网络整理| 查看: 265

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= 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() {} }

如果Integer对象的数值在上述范围之外,会比较Integer对象,此时如果再用“==”会比较出两个对象地址不同。

比较两个Integer的值是否相同,方法比较多,推荐用Objects.equals(a, b),这个还可以避免一些空指针问题的出现。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3