我想做一个简单的存储类,它将存储不同的类实例。我设法做的唯一几乎正确的方式是使用未经检查的类型转换。Java - 混合类型容器(非泛型类)可能没有未经检查的转换?
HashSet<T> result = (HashSet<T>) storage.get(s);
是否可以不选中铸造和未做类通用(class Storage<T> { }
)做了什么?
import java.util.*;
import org.junit.*;
class Tests {
@Test
public static void main (String[] args) {
Storage storage = new Storage();
HashSet<Child1> child1Set = storage.get("child1");
HashSet<Child1> duplicateChild1Set = storage.get("child1");
Assert.assertNotNull(child1Set);
Assert.assertSame(child1Set, duplicateChild1Set);
HashSet<Child2> child2Set = storage.get("child2");
Assert.assertNotNull(child2Set);
Assert.assertNotSame(child1Set, child2Set);
}
}
class Storage {
public Map<String, HashSet<? extends Parent>> storage = new HashMap<>();
public <T extends Parent> HashSet<T> get(String s) {
HashSet<T> result = (HashSet<T>) storage.get(s);
if (result == null) {
result = new HashSet<>();
storage.put(s, result);
}
return result;
}
}
class Parent { }
class Child1 extends Parent { }
class Child2 extends Parent { }
这种未经检查的类型转换是安全的,您不应该担心它。你甚至可以压制 - “@SuppressWarnings(”unchecked“)'。不幸的是,这就是您创建Heterogenous类型安全容器的方式。 –