Hashtable 鍵值唯一、查找 O(1)、線程安全,適合快速過濾重複字串。雖現代多用 HashSet/LinkedHashSet,但 Hashtable 邏輯清晰,適合教學與舊版本相容專案。
public String[] distinct(String[] arr) {
Hashtable ht = new Hashtable<>();
for (String s : arr) if (!ht.containsKey(s)) ht.put(s, s);
String[] result = new String[ht.size()];
int i = 0;
for (Enumeration e = ht.keys(); e.hasMoreElements(); ) result[i++] = e.nextElement();
return result; // 注意:Hashtable 無序,結果順序不固定
}
public String[] difference(String[] A, String[] B) {
Hashtable setB = new Hashtable<>();
for (String s : B) setB.put(s, s);
Hashtable diff = new Hashtable<>();
for (String s : A) if (!setB.containsKey(s)) diff.put(s, s);
String[] result = new String[diff.size()];
int i = 0;
for (Enumeration e = diff.keys(); e.hasMoreElements(); ) result[i++] = e.nextElement();
return result;
}
public String[] remove(String[] arr, String target) {
Hashtable ht = new Hashtable<>();
for (String s : arr) if (!s.equals(target)) ht.put(s, s);
String[] result = new String[ht.size()];
int i = 0;
for (Enumeration e = ht.keys(); e.hasMoreElements(); ) result[i++] = e.nextElement();
return result;
}
LinkedHashSet 或手動維護 ArrayList + HashSet。Arrays.stream(arr).distinct().toArray(String[]::new)。Hashtable 為同步類別,高併發場景建議改用 ConcurrentHashMap 或無鎖集合。