public boolean equals(Object obj) {
if (!(obj instanceof Person)) return false;
Person other = (Person) obj;
return name.equals(other.name)
&& birthYear == other.basicYear
&& Arrays.equals(raw, other.raw);
}
Object**,不可為具體類equals(null) 返回 false,不拋異常==,數組用 Arrays.equals()public int hashCode() {
return a.hashCode() + b.hashCode() + c + Arrays.hashCode(d);
}
x.equals(y) == true → x.hashCode() == y.hashCode()(強制)hashCode() != y.hashCode() → equals() == false(逆否命題)equals() == false 但 hashCode() 相同,但應盡量分散以提升性能return 0 合法但會癱瘓 HashMappublic int compareTo(Person other) {
int cmp = firstName.compareTo(other.firstName);
if (cmp != 0) return cmp;
cmp = lastName.compareTo(other.lastName);
if (cmp != 0) return cmp;
return Integer.compare(birthdate, other.birthdate);
}
Comparable<T> 泛型版本,避免原始類型擦除警告Comparator.compare() 邏輯一致public Values clone() {
try {
Values result = (Values) super.clone(); // 淺拷貝
result.bars = result.bars.clone(); // 數組深拷貝
result.hired = result.hired.clone(); // 可變對象深拷貝
return result;
} catch (CloneNotSupportedException e) {
throw new AssertionError(e); // 不可能發生
}
}
super.clone() 獲取淺拷貝對象Cloneable 的類 clone() **不拋受檢異常**,捕獲後包裝或忽略int factorial(int n) {
if (n < 0) throw new IllegalArgumentException("未定義");
if (n >= 13) throw new ArithmeticException("溢出");
if (n == 0) return 1;
return n * factorial(n - 1);
}
int findIndex(List<String> list, String target) {
if (list == null || target == null) throw new NullPointerException();
// ...
}
void frob(byte[] b, int index) {
if (b == null) throw new NullPointerException();
if (index < 0 || index >= b.length) throw new IndexOutOfBoundsException();
}
void frob(byte[] b, int off, int len) {
if (off < 0 || off > b.length || len < 0 || b.length - off < len)
throw new IndexOutOfBoundsException();
}
原則:顯式檢查所有前置條件,寧可拋異常也不可產生難以定位的邏輯錯誤。
| 操作 | 手寫循環 | 標準庫優選 |
|---|---|---|
| 填充 | for(i) a[i]=v | Arrays.fill(a, v) |
| 複製 | for(i) b[to+i]=a[from+i] | System.arraycopy(a,from,b,to,len) |
| 擴容/縮容 | 新建數組循環複製 | Arrays.copyOf(a, newLen) |
| 4字節↔int | 位運算組合 | 手寫位運算(無庫方法),注意用 >>> 無符號右移 |
這些「經典用法」看似基礎,實則是高質量 Java 代碼的基石。equals/hashCode 契約決定集合行為,clone 深拷貝關係數據隔離,防禦性編程構建健壯邊界,標準庫方法保證性能與正確性。**養成肌肉記憶,寫出經得起生產環境考驗的代碼。**