java - 列表和 map 的通用集合?

标签 java list collections types dictionary

是否有一个通用集合可以用于列表和映射参数,目的只是检查非空和大小?

现在我有一个具有以下方法的验证类:

// Check if the given List is not null, nor empty
public static <E> boolean listNotNull(List<E> l, boolean checkSize, int size)
{
    // List is null: return false
    if(l == null)
        return false;

    // List is smaller or equal to given size: return false
    if(checkSize && l.size() <= size)
        return false;

    // Everything is OK: return true
    return true;
}

然后我可以这样使用:

if(V.listNotNull(myList, true, 0)){ // if(myList != null && myList.size() > 0){
    // myList is not null, nor empty:
    ...
}

if(V.listNotNull(myList, true, 1)){ // if(myList != null && myList.size() > 1){
    // myList is not null, and has at least 2 items:
    ...
}

if(V.listNotNull(myList, false, 0)){ // if(myList != null){
    // myList is not null, but might still be empty:
    ...
}

我对列表使用这种通用验证方法,但在一种方法中我使用 HashMap。有了这个 HashMap,我想再次检查相同的内容(不是 null,也不是空):

if(myHashMap != null && myHashMap.size() > 0){
    // myHashMap is not null, nor empty:
    ...
}

是否可以替换List<E>在我的验证方法的参数中添加其他内容(例如 Collection<???> ),所以我同时包含列表和 map ?

或者我应该创建一个完全相同的新方法,但我使用 Map 作为参数而不是列表,如下所示:

// Check if the given Map is not null, nor empty
public static <K, E> boolean mapNotNull(Map<K, E> m, boolean checkSize, int size)
{
    // Map is null: return false
    if(m == null)
        return false;

    // Map is smaller or equal to given size: return false
    if(checkSize && m.size() <= size)
        return false;

    // Everything is OK: return true
    return true;
}

if(V.mapNotNull(myHashMap, true, 0)){ // if(myHashMap != null && myHashMap.size() > 0){
    // myHashMap is not null, nor empty
    ...
}

最佳答案

不,没有这样的接口(interface)或父类(super class)。当然可以基于Object来进行空检查。但没有与 size 方法或类似的通用接口(interface)。

关于java - 列表和 map 的通用集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24487646/

相关文章:

c++ - 使用指针从 std::list 中删除元素?

java - 带有 GNU trove 的整数排序集

java - 如何将 HashMap 显示为空 {} 而不是 null

java - 将自定义注释 Hook 到 Maven 中的 JUnit 测试器

java - 如何将数据从一个 Web 应用程序发送到另一个 Web 应用程序

Python:整数列表

C# 使用 List<T> 属性初始化类

java - 具有队列基​​本功能的最快 Java 集合是什么?

Java抽象类型类编译时检查

java - 将边列表转换为邻接列表