天天看点

开发日常小结(34):源码分析:String类的equals()方法

目录

​​1、提出问题​​

​​2、源码分析​​

​​3、测试Demo:​​

1、提出问题

我们都知道,在Java中,“==”比较的是对象在内存中的地址,“equals”比较对象的内容;今天复习一下”equals“。

2、源码分析

    /**

     * 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) {
        //First:比较两个对象是否是同一个对象,则直接return true;
        if (this == anObject) {
            return true;
        }

        //Second:如果被比较的对象是String类型,则继续
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            
            //Third:比较两者的长度
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;

                //Forth:比较两者元素是否相同
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }      

3、测试Demo:

public class test_equals {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
     String a="1234";
         String b="1234";
         String c = new String("1234");
         System.out.println("a==b: "+(a==b));
         System.out.println("a==c: "+(a==c));
         System.out.println("a.equals(c): "+(a.equals(c)));
  }

}