Java equals函数详解


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. 小知识,大麻烦。

相关内容