Reputation: 19
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
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
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
Reputation: 109547
return stringList.remove(stringList.size() - 1);
The rest can be removed, as remove
returns the removed item.
Upvotes: 4
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
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