String类的equals是如何进行字符串比较的

如题所述

1.equals方法的定义:

2.案例

public static void main(String[] args) {
String    a="aaaa";
String    b="bbb";
String    d="aaaa";

boolean c = a.equals(b);
System.out.println("c:"+c);
boolean e = a.equals(d);
System.out.println("e:"+e );



}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-07-17

String 的 equal是覆盖object类的

这是object类的equal方法

/* @param   obj   the reference object with which to compare.
* @return  {@code true} if this object is the same as the obj
*          argument; {@code false} otherwise.
* @see     #hashCode()
* @see     java.util.HashMap
*/
public boolean equals(Object obj) {
    return (this == obj);
}

再来看看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;
}

看代码多次判断比较

若当前对象和比较的对象是同一个对象,即return true。也就是Object中的equals方法。

若当前传入的对象是String类型,则比较两个字符串的长度,即value.length的长度。

若长度不相同,则return false

若长度相同,则按照数组value中的每一位进行比较,不同,则返回false。若每一位都相同,则返回true。

若当前传入的对象不是String类型,则直接返回false

相似回答