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

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -