java - How to avoid possible Null Pointer deference -
i have made simple add
method takes 2 args. here code :
public list<mylisttype> add(list<mylisttype> mytypes, mylisttype mytype) { if (mytypes == null) { mytypes = new arraylist<mylisttype>(); } int size = mytypes.size(); if (size > 1) { boolean laststatus = mytypes.get(mytypes.size()-1).getavailabilitystatus(); boolean secondlastelement = mytypes.get(mytypes.size() - 2).getavailabilitystatus(); if (laststatus == null && secondlastelement == null) { mytypes.remove(mytypes.size()-1); } else if (laststatus.equals(secondlastelement)) { mytypes.remove(mytypes.size()-1); } } mytypes.add(mytype); return mytypes; }
i think there possible null pointer deference in if
condition, on laststatus
. see can in order avoid ?
thanks.
assuming you're using java 7+, can use objects.equals
, takes care of both conditions:
boolean secondlastelement = mytypes.get(mytypes.size() - 2).getavailabilitystatus(); if (objects.equals(laststatus, secondlastelement)) { mytypes.remove(mytypes.size()-1); }
Comments
Post a Comment