Returning an element from a list in java -
can tell me advantages (if there advantage) of using getthelastelement2()
instead of getthelastelement()
? mean why necessary create reference obj
when easier return result?
import java.util.arraylist; import java.util.list; public class test { list list; test(arraylist list){ this.list = list; } public object getthelastelement(){ if (list.isempty()) return null; else return list.get(list.size()-1); } public object getthelastelement2(){ object obj; if (list.isempty()) obj = null; else obj = list.get(list.size()-1); return obj; } }
there no difference between these 2 implementations: obj
reference optimized away.
you slight advantage when debugging code, because can set breakpoint on return
statement of getthelastelement2
, , know going hit. in contrast getthelastelement
, need 2 breakpoints examine return value.
note else
in first example redundant:
public object getthelastelement(){ if (list.isempty()) { return null; } return list.get(list.size()-1); }
you further shrink single ternary expression:
public object getthelastelement(){ return !list.isempty() ? list.get(list.size()-1) : null; }
Comments
Post a Comment