首页 > 其他 > 详细

"asd".equals(s)与s.equals("asd")为什么前者可避免NullPointerException

时间:2014-03-19 12:07:19      阅读:387      评论:0      收藏:0      [点我收藏+]

 下图为String源码bubuko.com,布布扣

讲上图中 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;
 }

"asd".equals(s)与s.equals("asd")为什么前者可避免NullPointerException,布布扣,bubuko.com

"asd".equals(s)与s.equals("asd")为什么前者可避免NullPointerException

原文:http://www.cnblogs.com/IT-WJ/p/3607553.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!