shanglawt
shanglawt

Reputation: 19

How should I change it to remove the last element from this list?

I am trying to remove the last element from an arraylist but pop() method here is not working as I wanted. How should I change the code?

public String pop(){
    String last;
    if (stringList.size() == 0){
        return null;    

    } else {
        last = stringList.get(stringList.size()-1);
        return last;
        stringList.remove(stringList.size() - 1); //This is giving me error!
           }
}

Upvotes: 0

Views: 88

Answers (6)

Basil Bourque
Basil Bourque

Reputation: 338516

List#getLast & List#removeLast

In Java 21+, List is a SequencedCollection. See JEP 431: Sequenced Collections.

So now List offers convenient methods such as getLast and removeLast.

String lastString = myStringList.getLast() ;
myStringList.removeLast() ;

Upvotes: 0

Kamlesh Meghwal
Kamlesh Meghwal

Reputation: 4972

Because you are executing return last; statement before stringList.remove(stringList.size() - 1); and any statement after return statement never executed.

Modified code:

else {
    last = stringList.get(stringList.size()-1);
    stringList.remove(stringList.size() - 1); //Now it wont give any error!
    return last;
        }

Upvotes: 0

Joop Eggen
Joop Eggen

Reputation: 109547

return stringList.remove(stringList.size() - 1);

The rest can be removed, as remove returns the removed item.

Upvotes: 4

Rahul
Rahul

Reputation: 45060

Any statement after a return statement won't be accessible(unreachable code error). return statements should generally be the last statement you wish to execute in a method().

Bubble up the statement giving the error above the return and the code should work just fine.

stringList.remove(stringList.size() - 1); //goes above the return
return last;

Upvotes: 0

SpringLearner
SpringLearner

Reputation: 13844

Return statement should be at last because compiler assumes that there is nothing after return statement and it may say unreachable statement

Upvotes: 1

Blank Chisui
Blank Chisui

Reputation: 1073

code behind a return statement can never be executed.

Upvotes: 1

Related Questions