欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Object:所有类的超类--equals() & hashCode()、== 和 equals.() 两者均可用于比较两个对象是否相等

程序员文章站 2024-03-22 17:38:10
...

Object ????

Object 类是Java中所有类的始祖,在Java中每个类都扩展了Object。

如果没有明确地指出超类,Object就被认为是这个类的超类。

在Java中,只有基本数据类型不是对象,例如,数值、字符和布尔类型的值都不是对象。

所有的数组类型,不管是对象数组还是基本类型的数组都扩展了Object类。

——Core Java Volume I

如无特殊说明一下代码块,均采取 JDK8 源码分析。

equals 方法

== 和 equals.() 两者均可用于比较两个对象是否相等

==

  1. 基本类型(byte、short、int、long、float、double、char、boolean)

    判断值是否相等

  2. 引用类型(String类型或其他对象)

    判断地址值是否相等

不能使用 == 运算符检测两个字符串是否相等,它只能判断两个字符串的地址值是否相等。

  1. 包装类(Integer、Long等)

    /**
         * 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 {@code -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) {
                    try {
                        int i = parseInt(integerCacheHighPropValue);
                        i = Math.max(i, 127);
                        // 最大的数组大小是 Integer.MAX_VALUE
                        h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                    } catch( NumberFormatException nfe) {
                        // 如果属性不能被解析为int型,忽略它。
                    }
                }
                high = h;
    
                cache = new Integer[(high - low) + 1];
                int j = low;
                for(int k = 0; k < cache.length; k++)
                    cache[k] = new Integer(j++);
    
                // range [-128, 127] must be interned (JLS7 5.1.7)
                assert IntegerCache.high >= 127;
            }
    
            private IntegerCache() {}
        }
    
     public static Integer valueOf(int i) {
            if (i >= IntegerCache.low && i <= IntegerCache.high)
               return IntegerCache.cache[i + (-IntegerCache.low)];
            return new Integer(i);
        }
    

    对于Integer var = ? 在-128 ~ 127之间的赋值,Integer对象是在IntegerCache.cache产生,会复用已有对象,这个区间内的Integer值可以直接使用 == 进行比较。但是在这个区间外的所有数据都会在堆上产生,并不会复用已有对象。

    自动装箱规范要求 boolean、byte、char <= 127,介于 -128 和 127(包含)之间的short 和 int 被包装到固定的对象中。

    所有包装类对象间值的比较,请使用 equals 方法。

equals.()

  1. Object.equals.()
    public boolean equals(Object obj) {
        return (this == obj);
    }

不重写equals方法与“ == ”一样,用于比较对象的引用是否相等。

  1. Objects.equals()
    public static boolean equals(Object a, Object b) {
        return (a == b) || (a != null && a.equals(b));
    }

java.util.objects 允许比较对象为null,两者均为null时返回true,其中一个对象为null返回false,两者都不为null就调用 Object.equals()进行判断。

  1. 重写equals方法
  • String.equals.()
    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }
  • Integer.equals.()
    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

重写equals方法的规则(Java语言规范要求)

自反性

对于任何非空引用x,x.equals(x)应该返回true。

对称性

对于任何引用x和y,当且仅当y.equals(x)时,x.equals(y)返回true。

传递性

对于任何引用x,y,z,如果x.equals(y)返回true,y.equals(z),返回true,x.equals(z)也应该返回true。

一致性

如果x和y引用的对象没有发生变化,反复调用x.equals(y)应该返回同样的结果。

x.equals(null)

对于任意非空引用x,x.equals(null)应该返回false。

hashCode 方法

hashCode()可以获取散列码(hashcode),一个int整数。由于hashCode方法定义在Object类中,因此每个对象都有一个默认的hashcode,它的值由对象的存储地址得出。

重写hashCode方法

  1. String
    public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }
  1. 自定义重写hashCode()

当需要组合多个hashcode来作为对象的散列值时,可以调用 Object.hash 并提供所有需要组合的参数。

    public static int hash(Object... values) {
        return Arrays.hashCode(values);
    }

总结

两个相等的对象要求返回相等的 hashcode 。

重写equals方法必须重写 hashCode 方法。

如果x.equals(y)返回 true ,那么 x.hashCode() 就必须于 y.hashCode() 相等。