-2

How to avoid null insertion in ArrayList while inserting element?

ArrayList<String> al=new ArrayList<String>();
al.add(null);//should avoid
.
.
.
al.add("Ramesh");
Alya'a Gamal
  • 5,624
  • 19
  • 34
Ramesh Basantara
  • 21
  • 1
  • 1
  • 1

4 Answers4

2

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.

Maroun
  • 94,125
  • 30
  • 188
  • 241
  • 1
    Exactly. seems OP overlooking at his problem. – Suresh Atta Feb 06 '14 at 10:49
  • Can you please give example bugs by avoiding null? – Abimaran Kugathasan Feb 06 '14 at 10:51
  • @KugathasanAbimaran Suppose you're inserting Strings after you perform some operation on it to the `ArrayList`. Now suppose that at some point, you failed to perform something on a String and as a result you return `null`. If you don't insert it, you might think that all Strings were fine.. – Maroun Feb 06 '14 at 10:53
1

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)

  • add(E e)
  • add(int index, E element)
  • addAll(Collection c)
  • addAll(int index, Collection c)
  • set(int index, E element)
sk22
  • 837
  • 1
  • 10
  • 21
Mikescher
  • 875
  • 2
  • 16
  • 35
1

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

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
  • Extends class is more sexy for me.. Anyway you don't need to return the instance of the arraylist. Or at least use al = add () everytime. Just add (al, ..) – Marco Acierno Feb 06 '14 at 10:59
0
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");
stan
  • 984
  • 10
  • 15