webpersistence
webpersistence

Reputation: 904

Returning an element from a list in java

Can you tell me what are the advantages (if there is any advantage) of using getTheLastElement2() instead of getTheLastElement()? I mean why is it necessary to create the reference obj when it is easier just to return the 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;
    }
}

Upvotes: 2

Views: 136

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726929

There is no difference between these two implementations: the obj reference will probably be optimized away.

You do get a slight advantage when debugging the code, because you can set breakpoint on the return statement of getTheLastElement2, and know that it is always going to be hit. This is in contrast with getTheLastElement, where you would need two breakpoints to examine the return value.

Note that else in the first example is redundant:

public Object getTheLastElement(){
    if (list.isEmpty()) {
        return null;
    }
    return list.get(list.size()-1);
}

You could further shrink this to a single ternary expression:

public Object getTheLastElement(){
    return !list.isEmpty() ? list.get(list.size()-1) : null;
}

Upvotes: 2

Priyansh Goel
Priyansh Goel

Reputation: 2660

No, there is no advantage. Also, you should return list.get(list.size()-1)

Upvotes: 1

Related Questions