我希望检查一个Map、HashMap、ArrayList、List或者任何Collections中的内容是否为空或null?
我有下面这段代码,但是当我传递一个Map时它不起作用:
protected static <T extends Collection, Map> boolean isCollectionMapNullOrEmpty(final T c) {
if (c == null) {
return true;
}
return c.isEmpty();
}
失败:
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));
<T extends Collection, Map>
声明了两个类型变量:T
受原始Collection
限制,而Map
则没有限制。 - Savior