java - Instantiation of InternetAddress cause NPE although check -


guys thought java ignoring check null value, after careful inspection , debugging here's silly code part of huge program. cannot post entire method should point across.

public class nullcheck { public static void main(string[] args) {      arraylist<string>copied = new arraylist<string>();     copied.add("bg@ascii.com");     copied.add(null);      /* built mimemessage msg = new mimemessage(session); */     internetaddress[] copiedpeople = new internetaddress[copied.size()];     (int = 0; < copied.size(); i++)     {         string reccc = (string)copied.get(i);         if ((reccc != null) && (!reccc.equalsignorecase(""))) {             try {                 copiedpeople[i] = new internetaddress((string)copied.get(i));             } catch (addressexception e) {                 // todo auto-generated catch block                 e.printstacktrace();             }         }     }             // crash here //  msg.addrecipients(message.recipienttype.cc, copiedpeople); } } 

i know code fine because runs no problem 1st 14 iterations. again thought null check being ignored not! when internetaddress array instantiated set [null,null] loop ignores second item in arraylist when loop finished call addrecepients, arraylist still has 2nd null instantiation!! how remedy this?

you need use different algorithm. looks addrecipients requires none of recipients null. in case, need pass array of right length. easiest way remove null elements copied, pass copied.toarray() second parameter.

int = 0; while(i < copied.size()) {         string reccc = (string)copied.get(i);         if ((reccc == null){             copied.remove(i);         }         else{             i++;         } } msg.addrecipients(message.recipienttype.cc, copied.toarray()); 

if can't alter copied arraylist, can create new array list first, not add nulls it, use toarray on version without nulls.


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -