0

I was trying to create a generic method for checking if an item exists within a HashMap. Simple enough concept, but Java does not like what I'm trying to do. Is this even possible? This was my attempt.

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;
}

This is called in the following section of code:

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)) ...
}

I wanted this method to be generic for saving code and simplicity, as i have 4 different HashMaps to check. All of them are String keys, but they are all of different Value types as shown above.

If there is any way to make this generic, any help is welcome!

Kris Rice
  • 559
  • 1
  • 5
  • 23
  • Why can't you use `files.containsKey('someStringKey');` and likewise for others? – Raf Nov 08 '18 at 01:55
  • @Raf post as answer please – Kris Rice Nov 08 '18 at 02:00
  • There already is a question on how to use `Hashmap.containsKey()` see here https://stackoverflow.com/questions/3626752/key-existence-check-in-hashmap – Raf Nov 08 '18 at 02:06
  • Are you actually looking to see if has a key? The way I read your question I thought you were looking to see if the map contains a value. – Katie.Sun Nov 08 '18 at 02:19

3 Answers3

1

Let's make use of Map.get(Object) here, and the fact that it will return null if the key doesn't exist.

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

This will also take advantage of the O(1) access time of hashmaps without relying on an O(n) loop over entries.

MeetTitan
  • 3,383
  • 1
  • 13
  • 26
1

you can write generic method using T type parameter, you can use this method for all different types of HashMap

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

}
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
1

Why are you re-inventing the wheel? Map has containsKey() which does exactly as you want.

Bernie
  • 2,253
  • 1
  • 16
  • 18