How to get the last value of an ArrayList in Java?
How to get the last value of an ArrayList in Java?
20521-Aug-2023
Updated on 23-Aug-2023
Home / DeveloperSection / Forums / How to get the last value of an ArrayList in Java?
How to get the last value of an ArrayList in Java?
Aryan Kumar
23-Aug-2023Sure, there are a few ways to get the last value of an ArrayList in Java.
Here are two ways to get the last value of an ArrayList:
.get()
method:Java
In this example, the
myList
variable is an ArrayList that has the values 1, 2, and 3. The.get()
method returns the element at the specified index. ThelastValue
variable is assigned the value of the last element in the ArrayList, which is 3..size()
and.get()
methods:Java
In this example, the
myList
variable is an ArrayList that has the values 1, 2, and 3. The.size()
method returns the number of elements in the ArrayList. The.get()
method returns the element at the specified index. ThelastValue
variable is assigned the value of the last element in the ArrayList, which is 3.Which method you use depends on your specific needs. If you need to get the last value and you don't need to do any further processing on the element, then the
.get()
method is a good option. If you need to do further processing on the element, then the.size()
and.get()
methods is a good option.