== 和 equal 的區(qū)別

2018-07-03 14:50 更新
  • == 比較引用的地址
  • equel 比較引用的內(nèi)容 (Object 類本身除外)

  1. String obj1 = new String("xyz");
  2. String obj2 = new String("xyz");
  3. // If String obj2 = obj1, the output will be true
  4. if(obj1 == obj2)
  5. System.out.printlln("obj1==obj2 is TRUE");
  6. else
  7. System.out.println("obj1==obj2 is FALSE");
  8. // It will print obj1==obj2 is False
  9. // If String obj2 = obj1, the output will be true

默認(rèn)的, equals() 方法實際上和 “==” 在 object 類里是一樣的. 但是這個方法在每一個子類里都會被覆寫用來比較引用的內(nèi)容 (因為每個類都繼承了 object 類并覆寫了這個方法)

  1. String obj1 = new String("xyz");
  2. String obj2 = new String("xyz");
  3. if(obj1.equals(obj2))
  4. System.out.printlln("obj1==obj2 is TRUE");
  5. else
  6. System.out.println("obj1==obj2 is FALSE");
  7. Resultat: obj1==obj2 is TRUE
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號