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) {
list1.addAll(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 Integer
s, everything messed up.
But if you write
public void foo(List<?> list1, List<?> list2) {
list1.addAll(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.