作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
public class Hashing<Key, Elem>
我想检查 Key 是否是一个 int,所以我将这几行放在构造函数中:
Key key = null;
if (!(key instanceof Integer)) {
throw new TypeOfKeyStillNotSupportedException();
}
但是,我是这样创建的:
tHash = new Hashing<Integer, Movie>(max);
然后该死的 TypeOfKeyStillNotSupportedException() 弹出。为什么会发生这种情况,我该如何正确处理?
提前致谢。
编辑:已经发现问题出在键被分配为空。现在的问题是:如何检查?
最佳答案
null
不是 instanceof
任何事物。由于类型删除,无法检查 Key
的类型直接在运行时。一种选择是让用户传入 Class<Key>
到构造函数,以便您可以检查:
public Hashing(Class<Key> keyType, ...) {
if (keyType != Integer.class) {
throw new TypeOfKeyStillNotSupportedException();
}
...
}
...
Hashing<Integer, Foo> hashing = new Hashing<Integer, Foo>(Integer.class, ...);
为了避免重复类型参数,您可以创建一个静态工厂方法:
public static <K, E> Hashing<K, E> create(Class<K> keyType, ...) {
return new Hashing<K, E>(keyType, ...);
}
...
Hashing<Integer, Foo> hashing = Hashing.create(Integer.class, ...);
关于Java:检查泛型是否为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5878130/
我是一名优秀的程序员,十分优秀!