[英]Multiple generic type for a class java
有沒有辦法在不設置最大數量的情況下使用具有泛型類型的類? 我有這門課
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>
包含數據。
我希望HashMap
中的每個HashSet
都包含不同的類類型。 更准確地說,我希望泛型類型V
對於HashMap
中的每個HashSet
都不同
如何修復代碼以實現此結果?
您不能添加諸如Repository<V>
之類的類參數並期望V
對於映射中的每種類型的條目都不同。
但是,您可以執行以下操作:
從存儲庫中刪除泛型類型:
public class Repository {
}
生成存儲庫映射,以便將Class<?>
作為鍵(而不是字符串)和Set<?>
作為值):
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)
並且您將無法在返回的Set<T>
中插入不是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 泛型(除了getRepository
方法中使用的方法<T>
,您無論如何都需要執行未經檢查的演員表)。
沒有辦法干凈地實現這一目標。 您可以為您擁有的每種類型創建一個存儲庫,但您不能使用此設置將它們合並到一個存儲庫中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.