java - 阻止添加空元素的集合实现

标签 java

HashSet Set 实现允许添加 null。是否有不允许 null 的 Collection 实现?我知道我可以删除 HashSet 上的 null,但我想知道是否可以限制它。

public static void main(String[] args) {
    Set<String> testing = new HashSet<String>();
    testing.add(null);
    testing.add("test");

    for(String str : testing){

    }

  }


//TreeSet allows null as well
 public static void main(String[] args) {
    TreeSet<String> testing = new TreeSet<String>();
    testing.add(null);

    for(String str : testing){
      System.out.println("testing");
    }

  }

最佳答案

TreeSet 适合您的要求。它的 add(Object) 方法 javadoc 声明

Throws:

NullPointerException - if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements

Java 6 中和 Java 7 .

此外,如果您正在寻找 Collection 实现(而不是 Set 实现),则有 others .

关于java - 阻止添加空元素的集合实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20957407/

相关文章:

java - 无法编译的代码 - 表达式的非法开头

java - 如何在从数据库获取值的地方制作可靠的下拉菜单

java - 从具有日期条件的数据库中选择值

java - 使用 XML 可绘制的 RadioButton 样式

java - 如何从java中读取字节数组中的数据

java - 如何用 Java 解析 .eml 文件

java - proguard 可以安全地降级 Java 类吗?

java - RecyclerView未从firebase数据库中获取数据

java - 在实现 native Toast 模块后使用来自 React Native 的 native 模块时未处理的 promise 拒绝

java - 我的 Java JSON 解析器出了什么问题?