一个问题不常被人回答缘由有多种,好比较少的人知道答案,或者是问题是一个不起眼的,大多数人没有注意到(但这个问题可能对你来讲是很是重要的)。咱们能够找到不少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原创翻译/原文连接工具