zoukankan      html  css  js  c++  java
  • Java中的==与equals()

    1.基本类型比较,直接可使用==与!=

    2.对象的比较, 必须使用equals()方法。

    实际上,若使用==来比较对象,其比较的是对象的引用,然而不同的引用永远也不可能相等。此时必须要去比较对象的内容,要使用equals()方法。

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

    从源码可以看到,equals()默认的还是去比较引用,需要重写此方法,才能表达出想要的结果。如比较字符串时

    public boolean equals(Object anObject) {
            if (this == anObject) {
                return true;
            }
            if (anObject instanceof String) {
                String aString = (String)anObject;
                if (!COMPACT_STRINGS || this.coder == aString.coder) { //coder用于对字节进行编码的编码的标识符,支持的值LATIN1,UTF16
    return StringLatin1.equals(value, aString.value);
                }
            }
            return false;
        }
    StringLatin1中重写的equals()
    @HotSpotIntrinsicCandidate
        public static boolean equals(byte[] value, byte[] other) {
            if (value.length == other.length) {
                for (int i = 0; i < value.length; i++) {
                    if (value[i] != other[i]) {
                        return false;
                    }
                }
                return true;
            }
            return false;
        }

    扯远了,就写这么多吧

  • 相关阅读:
    asp.net发布和更新网站
    细说 Form (表单)
    python之面向对象进阶3
    python之面向对象进阶2
    python之面向对象进阶
    python之面向对象
    python之模块与包
    python之常用模块(续)
    python 之常用模块
    迭代器和生成器函数
  • 原文地址:https://www.cnblogs.com/holiphy/p/13904979.html
Copyright © 2011-2022 走看看