zoukankan      html  css  js  c++  java
  • JAVA面试题:equals()方法和== 区别

    http://bbs.csdn.net/topics/390000725

    总结:

    equals在没重写之前和==一样,重写之后,equals只要内容一样即为true

    equals跟==一般情况下是等价的,但是对于String类型,它重写了equals方法,比较的是内容。默认情况下两个都是比较的引用地址,除非你重写equals方法。

    equals源码:

     public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = count;
            if (n == anotherString.count) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = offset;
            int j = anotherString.offset;
            while (n-- != 0) {
                if (v1[i++] != v2[j++])
                return false;
            }
            return true;
            }
        }
        return false;
        }

    版主解答:

    “但是经常说==两边对象是按地址在比较,而equals()是按内容在比较”这句话在排除根类Object以及没有自己重写equals方法的情况下是对的。

    即Object类中equals的实现就是用的==
    其他继承Object的equals方法基本上都重写了这个方法,比如String类的equals方法:

    XML/HTML code
     
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    equals
    public boolean equals(Object anObject)
    Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object. 
     
    Overrides:
    equals in class Object
    Parameters:
    anObject - The object to compare this String against 
    Returns:
    true if the given object represents a String equivalent to this string, false otherwise
    See Also:
    compareTo(String), equalsIgnoreCase(String)



    这是String的equals方法源码:

    Java code
     
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    public boolean equals(Object obj)
        {
            if(this == obj)
                return true;
            if(obj instanceof String)
            {
                String s = (String)obj;
                int i = count;
                if(i == s.count)
                {
                    char ac[] = value;
                    char ac1[] = s.value;
                    int j = offset;
                    int k = s.offset;
                    while(i-- != 0
                        if(ac[j++] != ac1[k++])
                            return false;
                    return true;
                }
            }
            return false;
        }
  • 相关阅读:
    nexus3.x Liunx私库安装教程 (亲测有用)
    nexus 3.x下载 3.18.1(maven 私服)
    halo项目源码本地部署解决方案
    gradle的安装配置
    raw.githubusercontent.com 访问不了
    springboot使用quartz解决调用不到spring注入service的问题
    Linux在不能使用yum的环境下安装pgsql(公司内网)
    idea 里面的maven依赖下载不了,以及mabtis依赖包错误
    关于oracle 数据库效率的优化
    关于oracle 不常用的job 运行时间设置
  • 原文地址:https://www.cnblogs.com/kenshinobiy/p/4652040.html
Copyright © 2011-2022 走看看