How to get the last value of an ArrayList
Get the last element of an ArrayList
using .get(list.size() - 1)
:
In this instance, last
would be "Third"
, the last item in our ArrayList.
Safe guards: Null and empty check
Checking if the list is empty or null is pivotal to prevent us from that heart-attack inducing IndexOutOfBoundsException
or NullPointerException
.
Check for empty ArrayList
Ask your list politely if it's empty before trying to get anything from it:
Handling null ArrayLists
Don't presume the list exists! Check first, or face the null's wrath:
Leveraging Guava for grace and simplicity
Are you a fan of Guava, Google's core Java libraries? There's an elegant way to get the last element without headaches:
Using Optional
helps communicate your intentions more clearly and provides null safety, while Iterables.getLast()
simplifies your code, making it more readable.
Efficiency for large lists: Time complexity
For large lists, time complexity matters just like real estate — it's all about location! Luckily, list.get(list.size() - 1)
is a constant time operation, not slowing down as the list grows.
Default values: Plan B for empty lists
Sometimes, a Plan B is helpful. Here's how to set default values for potentially empty lists:
Default values with Java Collections
Default values with Guava's Lists
Here's the Guava way of handing out a consolation prize when the list is empty:
Guava's Lists: Added functionality
Guava's Lists
hides additional surprises, such as getFirst()
. Remember to keep a sharp eye on your time complexity requirements when using these methods.
Intentional code: Best practices
Choose methods consciously based on your specific needs. In most scenarios, list.get(list.size() - 1)
offers a perfect balance of being direct and efficient, unless you're deep into Guava, making use of its additional benefits.
Was this article helpful?