3

I have a function prints Map objects,

public static void printMap(Map<Integer, Integer> map) {
    for (Map.Entry<Integer, Integer> entry : map.entrySet()) {          
        System.out.println( entry.getKey() + " " + entry.getValue() );
    }
}

Now, I want my function to work with Map<String, Integer> type of maps too. How to do it? I always wanted to use generics, hope to have a good start with this question.

4

3 回答 3

7

You can write generic methods as in below code:

public static <K, V> void printMap(Map<K, V> map) {
    for (Map.Entry<K, V> entry : map.entrySet()) {          
         System.out.println( entry.getKey() + " " + entry.getValue() );
    }
}

Suggested Read:


As pointed out by @JBNizet in comments, you can also write the method using wildcards (?) instead of type parameters as below:

public static void printMap(Map<?, ?> map) {
    for (Map.Entry<?, ?> entry : map.entrySet()) {          
         System.out.println( entry.getKey() + " " + entry.getValue() );
    }
}
于 2013-07-21T10:50:10.953 回答
2

You can do this with wildcard Map<? extends Object, Integer>. This line means that you can have anything that extends Object class. So it can be String, Integer, UserDefinedObject. Anything.

于 2013-07-21T10:50:33.137 回答
1

Doubt you need the method really - Use toString() of Map instance, that's it.

于 2013-07-21T10:51:10.533 回答