I want to check if a Map, HashMap, ArrayList, List or anything from Collections is Empty or null?
I have this, but its not working when I pass a Map:
protected static <T extends Collection, Map> boolean isCollectionMapNullOrEmpty(final T c) {
if (c == null) {
return true;
}
return c.isEmpty();
}
Failure:
List<String> aList = Arrays.asList("a1", "a2", "a4");
Map<String, Object> aMap = new HashMap<String, Object>();
aMap.put("a2", "foo");
aMap.put("a1", "foo");
aMap.put("a3", "foo");
aMap.put("a4", "foo");
System.out.println(isCollectionMapNullOrEmpty(aList)); // works
// fails with The method isCollectionMapNullOrEmpty(T) in the type LearnHashMap is not applicable for the arguments (Map<String,Object>)
System.out.println(isCollectionMapNullOrEmpty(aMap));
Your isCollectionMapNullOrEmpty
compiles and works, but not the way you intended.
<T extends Collection, Map>
You've declared two type variables, T
and Map
, where T
must be a Collection
. The type variable Map
has nothing to do with the interface Map
, and is in fact not even used. (Also, you used the raw Collection
interface here.) You are passing aList
which is a Collection
, so it compiles. However, aMap
is not a Collection
, so the compilation fails passing in a Map
.
It looks like you wanted T
to be either a Collection
or a Map
. But Java's generics don't work that way; you can't declare a type parameter to be one thing or another thing.
(As an aside, you can say one thing and another thing: T extends Collection & Map
, or without raw types, T extends Collection<?> & Map<?, ?>
, but I'm not aware of any classes that implement both interfaces.)
You can have two overloaded methods, one for a Collection
and one for a Map
, that will perform the same functionality. Here, I've taken advantage of short-circuiting to combine the statements:
protected static boolean isCollectionMapNullOrEmpty(final Collection<?> c) {
return c == null || c.isEmpty();
}
protected static boolean isCollectionMapNullOrEmpty(final Map<?, ?> m) {
return m == null || m.isEmpty();
}
Both methods have the same exact code, but because there is no super-interface declaring isEmpty
, this appears to be as good as it gets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With