手机版
你好,游客 登录 注册
背景:
阅读新闻

Java equals函数详解

[日期:2012-11-24] 来源:Linux社区  作者:xiaotian15 [字体: ]

equals函数在基类object中已经定义,源码如下

  1. public boolean equals(Object obj) { 
  2.        return (this == obj); 
  3.    } 

从源码中可以看出默认的equals()方法与“==”是一致的,都是比较的对象的引用,而非对象值(这里与我们常识中equals()用于对象的比较是相饽的,原因是Java中的大多数类都重写了equals()方法,下面已String类举例,String类equals()方法源码如下:)

  1. /** The value is used for character storage. */ 
  2. private final char value[]; 
  3.  
  4. /** The offset is the first index of the storage that is used. */ 
  5. private final int offset; 
  6.  
  7. /** The count is the number of characters in the String. */ 
  8. private final int count; 

 

  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 = count; 
  8.             if (n == anotherString.count) { 
  9.                 char v1[] = value; 
  10.                 char v2[] = anotherString.value; 
  11.                 int i = offset; 
  12.                 int j = anotherString.offset; 
  13.                 while (n-- != 0) { 
  14.                     if (v1[i++] != v2[j++]) 
  15.                         return false
  16.                 } 
  17.                 return true
  18.             } 
  19.         } 
  20.         return false
  21.     } 

String类的equals()非常简单,只是将String类转换为字符数组,逐位比较。

综上,使用equals()方法我们应当注意:

1. 如果应用equals()方法的是自定义对象,你一定要在自定义类中重写系统的equals()方法。

2. 小知识,大麻烦。

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款