Java 如何避免在 ArrayList 中插入空值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21600559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to avoid null insertion in ArrayList?
提问by Ramesh Basantara
How to avoid null insertion in ArrayList while inserting element?
插入元素时如何避免在ArrayList中插入空值?
ArrayList<String> al=new ArrayList<String>();
al.add(null);//should avoid
.
.
.
al.add("Ramesh");
回答by Mikescher
You could create your own ArrayList-Class (derived from the original) and override the Add-Method
Then you could check for null when Adding.
您可以创建自己的 ArrayList-Class(派生自原始)并覆盖 Add-Method
然后您可以在添加时检查 null。
@Override
public boolean add(E e) {
if (e == null) return false;
else return super.add(e)
}
As Mark stated in the comments you perhaps want to override all other possibilties of Adding values too. (see the doc)
正如马克在评论中所述,您可能也想覆盖添加值的所有其他可能性。(见文档)
- add(E e)
- add(int index, E element)
- addAll(Collection c)
- addAll(int index, Collection c)
- set(int index, E element)
- 添加(E e)
- 添加(整数索引,E 元素)
- addAll(集合 c)
- addAll(int 索引,集合 c)
- 设置(整数索引,E 元素)
回答by Maroun
Avoiding null
can be harmful sometimes and it could hide possible bugs.
避免null
有时可能是有害的,它可能会隐藏可能的错误。
If you're worried about getting NullPointerException
in some stage, you can simply check if the item stored in the ArrayList
is null
.
如果您担心进入NullPointerException
某个阶段,您可以简单地检查存储在ArrayList
is 中的项目null
。
You cannot disallow inserting null
to ArrayList
.
您不能禁止插入null
到ArrayList
.
回答by Ruchira Gayan Ranaweera
You can try something like that, But if you want to do exactly what you are trying you have to rewrite add()
in ArrayList
class. Using this validation you can avoid null
您可以尝试类似的方法,但是如果您想完全按照您正在尝试的方式进行操作,则必须add()
在ArrayList
课堂上重写。使用此验证,您可以避免null
public static void main(String[] args) {
ArrayList<String> al=new ArrayList<String>();
al=add(al,null);
al=add(al,"Ramesh");
al=add(al,"hi");
}
public static ArrayList<String> add(ArrayList<String> al,String str){
if(str!=null){
al.add(str);
return al;
}else {
return al;
}
}
In this case you have to call your custom add
method to add element
在这种情况下,您必须调用自定义add
方法来添加元素
回答by stan
ArrayList<String> al = new ArrayList<String>() {
@Override
public boolean add(String s ) {
if( s != null ) {
return super.add( s );
}
return false;
}
};
al.add(null);
al.add("blabla");