【发布时间】:2019-04-11 12:42:50
【问题描述】:
我试图创建一个通用方法来检查项目是否存在于 HashMap 中。很简单的概念,但 Java 不喜欢我正在尝试做的事情。这甚至可能吗?这是我的尝试。
private static boolean inMap(String file, HashMap<String, Object> map) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getKey().equals(file)) return true;
}
return false;
}
这在以下代码段中被调用:
private static Map<String, String> files = new HashMap();
private static Map<String, BufferedImage> images = new HashMap();
private static Map<String, Texture> textures = new HashMap();
private static Map<String, Model> models = new HashMap();
public static TexturedModel loadOBJModel(String file) {
if (inMap(file, files)) ...
}
public static Texture loadTexture(String file) {
if (inMap(file, textures)) ...
}
我希望这种方法是通用的,以节省代码和简单性,因为我有 4 个不同的 HashMap 需要检查。它们都是String键,但它们都是不同的Value类型,如上所示。
如果有任何方法可以使其通用,欢迎提供任何帮助!
【问题讨论】:
-
为什么你不能使用
files.containsKey('someStringKey');和其他人一样? -
@Raf 请发帖回答
-
已经有一个关于如何使用
Hashmap.containsKey()的问题看这里stackoverflow.com/questions/3626752/… -
你真的想看看是否有钥匙吗?我阅读您的问题的方式,我以为您正在查看地图是否包含值。
标签: java class dictionary generics hashmap