歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java equals函數詳解

Java equals函數詳解

日期:2017/3/1 10:06:46   编辑:Linux編程

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. /** The offset is the first index of the storage that is used. */
  4. private final int offset;
  5. /** The count is the number of characters in the String. */
  6. 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. 小知識,大麻煩。

Copyright © Linux教程網 All Rights Reserved