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
此外,如果您正在寻找 Collection
实现(而不是 Set
实现),则有 others .
关于java - 阻止添加空元素的集合实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20957407/