How to avoid null insertion in ArrayList while inserting element?
ArrayList<String> al=new ArrayList<String>();
al.add(null);//should avoid
.
.
.
al.add("Ramesh");
How to avoid null insertion in ArrayList while inserting element?
ArrayList<String> al=new ArrayList<String>();
al.add(null);//should avoid
.
.
.
al.add("Ramesh");
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 could create your own ArrayList-Class (derived from the original) and override the Add-Method
Then you could check for null when Adding.
@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)
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");