HashSet Set实现允许添加null。是否有任何Collection实现不允许null?我知道我可以对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状态


抛出:

NullPointerException-如果指定的元素为null且此集合
使用自然顺序,或其比较器不允许使用null元素


Java 6Java 7中。

另外,如果要查找Collection实现(而不是Set实现),则有others

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

10-11 22:21
查看更多