下图为String源码

讲上图中 if (  anObject instanceof Object)  改为if ( this instanceof Object && anObject instanceof Object) 后s.equals("asd")也可以避免NullPointerException

 

以下代码为仿照仿照上图重写的一个方法 :

 

public boolean equals(String str , Object anObject){
  
   if (str == anObject) {
      return true;
  }
  if ( str instanceof Object && anObject instanceof Object) {
      String anotherString = (String)anObject;
      int n = str.length();
      if (n == anotherString.length()) {
   char v1[] = str.toCharArray();
   char v2[] = anotherString.toCharArray();
   int i = 0;
   int j = 0;
   while (n-- != 0) {
       if (v1[i++] != v2[j++])
    return false;
   }
   return true;
      }
  }
  return false;
 }

posted on 2014-03-18 14:07  你猜呢  阅读(387)  评论(0编辑  收藏  举报