【问题标题】:Creating a method to check if a value exists in a generic HashMap in Java? [duplicate]创建一种方法来检查Java中的通用HashMap中是否存在值? [复制]
【发布时间】: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


【解决方案1】:

让我们在这里使用Map.get(Object),如果密钥不存在,它将返回null。

public static boolean contains(Map<?, ?> inMap, Object key) {
    return inMap.get(key) == null;
}

这也将利用哈希映射的 O(1) 访问时间,而不依赖于条目的 O(n) 循环。

【讨论】:

  • 你不用.get(),containsKey()就够了,就是O(1)
  • 完美,谢谢。完美运行!
  • @Raf 帖子作为答案,甚至不知道这存在。
【解决方案2】:

您可以使用T类型参数编写泛型方法,您可以将此方法用于所有不同类型的HashMap

public static <T> boolean contains(String file, T a) {
    return a.keySet().contains(file); //or a.containsKey(file);

}

【讨论】:

    【解决方案3】:

    为什么要重新发明轮子? Map 有 containsKey() 完全符合您的要求。

    【讨论】:

      猜你喜欢
      • 2019-04-20
      • 2014-09-14
      • 2014-12-19
      • 1970-01-01
      • 2016-02-27
      • 2020-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多