提供一組泛型、空安全、支援可變參數與 Collection的數學工具方法,避免業務代碼中重複編寫迴圈邏輯,並統一異常處理風格。
package com.happyelements.athene.game.util;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import java.util.Collection;
public final class MathUtil {
private MathUtil() {} // 工具類禁止實例化
// ==================== 最小值 ====================
public static <T extends Comparable<T>> T min(T... values) {
return min(Lists.newArrayList(values));
}
public static <T extends Comparable<T>> T min(Collection<T> values) {
Preconditions.checkNotNull(values, "集合不能為 null");
T min = null;
for (T t : values) {
Preconditions.checkNotNull(t, "集合元素不能包含 null");
if (min == null || t.compareTo(min) < 0) {
min = t;
}
}
return min; // 空集合返回 null
}
// ==================== 最大值 ====================
public static <T extends Comparable<T>> T max(T... values) {
return max(Lists.newArrayList(values));
}
public static <T extends Comparable<T>> T max(Collection<T> values) {
Preconditions.checkNotNull(values, "集合不能為 null");
T max = null;
for (T t : values) {
Preconditions.checkNotNull(t, "集合元素不能包含 null");
if (max == null || t.compareTo(max) > 0) {
max = t;
}
}
return max;
}
// ==================== 求和 ====================
public static Integer sum(Collection<Integer> values) {
Preconditions.checkNotNull(values, "集合不能為 null");
int sum = 0;
for (Integer v : values) {
Preconditions.checkNotNull(v, "集合元素不能包含 null");
sum += v;
}
return sum;
}
public static Integer sum(Integer... values) {
return sum(Lists.newArrayList(values));
}
}
| 決策點 | 選擇 | 理由 |
|---|---|---|
| 參數形式 | 可變參數 + Collection 重載 | 兼顧 min(1,2,3) 便利性與 min(list) 通用性 |
| 空集合行為 | 返回 null | 避免拋出異常打斷流程,調用方自行判斷 |
| null 元素處理 | Preconditions.checkNotNull 拋 NPE | 快速失效,暴露數據質量問題 |
| 泛型約束 | <T extends Comparable<T>> | 確保元素可比較,支援所有標準類型及自定義實現 Comparable 的類 |
| 依賴庫 | Guava (Preconditions, Lists) | 項目已引入,碼簡潔可靠;若無 Guava 可換為 JDK 原生判斷 |
// 可變參數調用
Integer minVal = MathUtil.min(5, 2, 9, 1); // 1
Integer maxVal = MathUtil.max(5, 2, 9, 1); // 9
Integer sumVal = MathUtil.sum(5, 2, 9, 1); // 17
// Collection 調用
List<Double> prices = Arrays.asList(19.9, 29.9, 9.9);
Double minPrice = MathUtil.min(prices); // 9.9
Double maxPrice = MathUtil.max(prices); // 29.9
// 自定義類型(需實現 Comparable)
List<User> users = ...;
User oldest = MathUtil.max(users); // 依賴 User.compareTo 實現
average()、median()、percentile() 等統計函數Comparator 參數版本,支援非自然順序比較Stream 版本利用並行流加速Optional 返回類型(Java 8+),更明確表達「可能為空」語義這個 MathUtil 類展示了工具類設計的最佳實踐:泛型復用、防禦性編程、API 對稱性、零依賴業務邏輯。將此類基礎設施沉澱到公共庫,能顯著降低業務代碼的圈複雜度與 Bug 率。