A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 高波 中级黑马   /  2013-6-25 20:51  /  1397 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 孙百鑫 于 2013-6-27 07:39 编辑

在毕老师讲RuntimeException中NullPointException时,提到了一点:
name.equals("lisi") 跟 "lisi".equals(name)。这两者的区别具体体现在什么地方?
大神们麻烦给个详细点的解答,有点纠结。
  1. class Person
  2. {
  3.         public void checkName(String name)
  4.         {
  5.                 if("lisi".equals(name))//if(name.equals("lisi"))
  6.                         System.out.println("YES");
  7.                 else
  8.                         System.out.println("no");
  9.         }
  10. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
孙百鑫 + 1

查看全部评分

6 个回复

倒序浏览
搞不懂有什么区别。占楼坐等大神解答
回复 使用道具 举报
。。这个我要去翻java源码了,,,先占座。。呵呵
回复 使用道具 举报
if("lisi".equals(name))//这句话如果传过来的name是null的话,返回false,程序是正常的
if(name.equals("lisi"))//这句话如果传过来的name是null的话,就会报nullPointExcetion,因为null怎么会有equals方法呢。

回复 使用道具 举报
boolean java.lang.String.equals(Object anObject)

equals
public boolean equals(Object anObject)
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
Overrides:
equals in class Object
Parameters:
anObject - The object to compare this String against
Returns:
true if the given object represents a String equivalent to this string, false otherwise
当且仅当该参数不为 null
区别就是
"123".equals(null);//false
null..equals("123");//抛 runtime

评分

参与人数 1技术分 +1 收起 理由
孙百鑫 + 1 神马都是浮云

查看全部评分

回复 使用道具 举报
就是为了防止空指针异常啊。如果name=null 就会空指针异常的,“lisa".equals(namel),代码更健壮,项目中一般都这么写
回复 使用道具 举报
楼主您好。我已将您的帖子改成已解决。如果帖子发布长时间没加分。及时联系我。以免漏分的情况发生{:soso_e100:}
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马