有沒有辦法在不設定最大數量的情況下使用具有泛型型別的類?我有這門課
public class Repository<V> {
private Map<String, HashSet<V>> repo = new HashMap<>();
private static Repository instance = null;
private Repository() {}
public static synchronized Repository getInstance() {
if(instance == null) {
instance = new Repository();
}
return instance;
}
public void addRepository(String key) throws ClassNotFoundException, IOException {
repo.put(key, new HashSet<>());
}
.....
}
這是一個“通用存盤庫”,其中HashMap包含一個識別符號作為鍵,而作為HashSet<V>資料的值。
我希望每個包含不同HashSet的HashMap型別別。更準確地說,我希望泛型型別V在HashSetHashMap
如何修復代碼以實作此結果?
uj5u.com熱心網友回復:
您不能添加類引數,例如Repository<V>并期望V地圖中每種型別的條目都不同。
但是,您可以執行以下操作:
從存盤庫中洗掉泛型型別:
public class Repository {
}
生成存盤庫映射,使其采用 aClass<?>作為鍵(而不是字串)和 aSet<?>作為值):
private final Map<Class<?>, Set<?>> repo = new HashMap<>();
然后,創建一個添加新存盤庫的方法和一個獲取現有存盤庫的方法:
public <T> void addRepository(Class<T> key) {
Set<?> existing = repo.putIfAbsent(key, new HashSet<>());
if (existing != null) {
throw new IllegalArgumentException("Key " key " is already associated to a repository");
}
}
public <T> Set<T> getRepository(Class<T> key) {
Set<?> subRepo = repo.get(key);
if (subRepo == null) {
throw new IllegalArgumentException("No repository found for key " key);
}
return (Set<T>) subRepo; //unchecked cast
}
注意:getRepository()將執行未經檢查的強制轉換,但它是“安全的”未經檢查的強制轉換,因為將新條目添加到地圖中的唯一方法是通過<T> void addRepository(Class<T> key),您將無法插入不在T回傳值中的值Set<T>。
示例用法:
Repository repository = Repository.getInstance();
repository.addRepository(String.class);
repository.addRepository(Integer.class);
Set<String> stringRepo = repository.getRepository(String.class);
stringRepo.add("Hey");
stringRepo.add("Jude");
Set<Integer> intRepo = repository.getRepository(Integer.class);
intRepo.add(1);
intRepo.add(4);
但是,我認為每種型別都應該有一個存盤庫,這樣會更干凈,因為使用上述解決方案,您基本上根本沒有利用 Java 泛型(方法<T>中使用的getRepository方法除外,您需要為此執行無論如何,未經檢查的演員表)。
uj5u.com熱心網友回復:
沒有辦法干凈地實作這一目標。您可以為您擁有的每種型別創建一個存盤庫,但您不能使用此設定將它們合并到一個存盤庫中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/494530.html
