现在的位置: 首页 > 综合 > 正文

【Java SE】==操作符和equals方法作用的区别

2013年04月22日 ⁄ 综合 ⁄ 共 784字 ⁄ 字号 评论关闭

这是String类的equals方法的源码:


 /**
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a {@code String}
     *          equivalent to this string, {@code false} otherwise
     *
     * @see  #compareTo(String)
     * @see  #equalsIgnoreCase(String)
     */
    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;
    }

此方法的作用是比较两个字符串的内容是否相等

==运算符的作用是比较两个引用变量的内存地址是否相同。




【上篇】
【下篇】

抱歉!评论已关闭.