Java int和Integer的区别

266 阅读2分钟

基础

int可以存储整数

Integer可以存储整数

Integer是int的包装类型

Integer是对象,可以为null

关键

== 比较两个变量

对于int来说,只要值相等,那就返回true,没什么好讲的 对于Intger,请看代码

public class Main {
    public static void main(String[] args) {

        Integer a = 127;
        Integer b = 127;

        Integer c = 128;
        Integer d = 128;

        Integer e = new Integer(10);
        Integer f = new Integer(10);
        Integer h = new Integer(10);
        Integer i = new Integer(10);

        System.out.println("用==直接判断");
        System.out.println(a == b);
        System.out.println(c == d);
        System.out.println(e == f);
        System.out.println(h == i);

        System.out.println();

        System.out.println("用equal()判断");
        System.out.println(a.equals(b));
        System.out.println(c.equals(d));
        System.out.println(e.equals(f));
        System.out.println(h.equals(i));
    }
}

输出结果

用==直接判断
true
false
false
falseequal()判断
true
true
true
true

我们倒着看上去

为什么equals方法比较都输出true呢

这非常简单

因为Integer类重写了equals方法

请看源码

public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

直接在比较value,那肯定返回true

为什么e == f 和 h ==i 返回false

这也非常简单,因为它们是对象,直接双等于号是在比较地址是否相同,它们都使用了new,都在堆中进行创建,地址自然不同,所以返回false

为什么 a == b 返回true,

c == d 返回false呢?

因为

关于 Integer 的值缓存,这涉及 Java 5 中另一个改进。构建 Integer 对象的传统方式是直接调用构造器,直接 new 一个对象。但是根据实践,我们发现大部分数据操作都是集中在有限的、较小的数值范围,因而,在 Java 5 中新增了静态工厂方法 valueOf,在调用它的时候会利用一个缓存机制,带来了明显的性能改进。按照 Javadoc,这个值默认缓存是 -128 到 127 之间。

也就是说,如果不实用new创建Integer对象,那么当数字在-128到127之间,可以直接用 == 比较,会返回true(因为它们地址相同,都在缓存中)

参考:leeeyou.gitbooks.io/java-36/con…