一個問題不常被人回答緣由有多種,好比較少的人知道答案,或者是問題是一個不起眼的,大多數人沒有注意到(但這個問題可能對你來講是很是重要的)。咱們能夠找到不少JAVA FAQs(最常被問到的問題),可是這裏只有最不常被回答的問題。html
有,這裏有一個例子,在忽略choice的值的狀況下,finally中的代碼將不會執行。java
try { if (choice) { while (true) ; } else { System.exit(1); } } finally { code.to.cleanup(); }
public class C { public boolean equals(C that) { return id(this) == id(that); } }
public class C { public boolean equals(Object that) { return (that instanceof C) && id(this) == id((C)that); } }
public class Hashtable { public Object get(Object key) { Object entry; ... if (entry.equals(key)) ... } }
public class C { public boolean equals(Object that) { return (this == that) || ((that instanceof C) && this.equals((C)that)); } public boolean equals(C that) { return id(this) == id(that); // Or whatever is appropriate for class C } }
public class C2 extends C { int newField = 0; public boolean equals(Object that) { if (this == that) return true; else if (!(that instanceof C2)) return false; else return this.newField == ((C2)that).newField && super.equals(that); } }
爲了使它正確執行,你必須當心若是對待equals方法。例如,檢查參數是不是C的對象,要使用instanceof C而不是that.getClass()==C.class.在equals方法中使用this.getClass()==that.getClass()的時候你必須保證兩個對象是同一個類型的。緩存
public class LinkedList { Object contents; LinkedList next = null; public boolean equals(Object that) { return (this == that) || ((that instanceof LinkedList) && this.equals((LinkedList)that)); } public boolean equals(LinkedList that) { // Buggy! return Util.equals(this.contents, that.contents) && Util.equals(this.next, that.next); } }
public static boolean equals(Object x, Object y) { return (x == y) || (x != null && x.equals(y)); }
翻譯水平有限,輕噴。app
OSCHINA.NET原創翻譯/原文連接工具