gabriel gabriel - 1 year ago 76
Java Question

Java HashMap as method parameter - not specifying the "value" type

This is a question about Java syntax. I am not stuck.

For lists, let's say I have a List of Strings.

List<String> mylist;

As long as I don't need to access the elements in my list, I can refer to this list as a

So I can have a method looking like that:

public int listSize(List list) {
return list.size();

Now let's assume I have a

HashMap<String, String> myhash;

And a method accessing the key but never the value:

public boolean hashContainsKey(HashMap<String, String> hash, String key) {
return hash.containsKey(key);

Is there a nice way to only specify the "key" part of the HashMap?

Something like

Answer Source

I wish your example is just something to demonstrate your idea instead of something you are going to write, as it is quite meaningless to write method like these.

One way is to use wildcard for the type param:

your first example should look like this

// Should be static in this example
public static int listSize(List<?> list) {
    return list.size();

and the other one should be:

// It is, imho, irrational to deal with HashMap specifically, 
// and again, this should be static
public static boolean mapContainsKey(Map<String, ?> map, String key) {
    return map.containsKey(key);

or even better:

public <T> static boolean mapContainsKey(Map<T, ?> map, T key) {
    return map.containsKey(key);

Little update on why use wildcard (List<?>) over raw type (List)

In OP's example, the difference may not be obvious. However they are not equivalent.

For example:

public void foo(List list1, List list2) {

The above is legal, but if you call it with foo(aStringList, anIntegerList);, the outcome will be disastrous: the String List will now contains Integers, everything messed up.

But if you write

public void foo(List<?> list1, List<?> list2) {

Although list1 and list2 allows any List<XXX> to pass in, without you explicitly telling the compiler that they are of the same type, compiler will assume the ? in list1 and the ? in list2 can represent different thing, and hence fail the compilation of list1.addAll(list2);, which avoid you writing stupid things like this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download