How to avoid null insertion in ArrayList?
This question already has an answer here:
Avoiding null
can be harmful sometimes and it could hide possible bugs.
If you're worried about getting NullPointerException
in some stage, you can simply check if the item stored in the ArrayList
is null
.
You cannot disallow inserting null
to ArrayList
.
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
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
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");
链接地址: http://www.djcxy.com/p/13302.html
上一篇: 在java中检查空引用的乐观方式
下一篇: 如何避免在ArrayList中的空插入?