String类底层源码(随时更新)

equals方法


 1  public boolean equals(Object anObject) {
 2         if (this == anObject) {
 3             return true;
 4         }
 5         if (anObject instanceof String) {
 6             String anotherString = (String)anObject;
 7             int n = value.length;
 8             if (n == anotherString.value.length) {
 9                 char v1[] = value;
10                 char v2[] = anotherString.value;
11                 int i = 0;
12                 while (n-- != 0) {
13                     if (v1[i] != v2[i])
14                         return false;
15                     i++;
16                 }
17                 return true;
18             }
19         }
20         return false;
21     }

1)先判断 anobject与this指向的区域是否相等,相等直接返回true

2)再判断  anobject是否为String类的实例

   不是就返回fasle,

   是的话 先把anobjec强t转为String类型.比较两者的(其实是字符数组)长度

                不一致直接返回false

                一致的话就按序比较每个字符,返回最终结果

 
原文地址:https://www.cnblogs.com/itjone/p/13837052.html