-4

I have an ArrayList containing a list of objects. I'm trying to figure out if the last element of the array contains an object equal to sn.i

arraylist.size() -1 returns an integer, so I can't use it to compare my object to.

Is there a way of doing this so it returns my object value instead of an integer?

Jordan Moffat
  • 337
  • 6
  • 17
  • 1
    You cannot ask such a beginners question here. Please, watch a beginners tutorial first. – nbro Nov 13 '14 at 21:02
  • You should just read https://docs.oracle.com/javase/7/docs/api/java/util/List.html – StackFlowed Nov 13 '14 at 21:06
  • @nbro I don't think this is a beginner question since you can see lots of attention which is the exact same question here [How to get the last value of array list](http://stackoverflow.com/questions/687833/how-to-get-the-last-value-of-an-arraylist) – Chit Khine Sep 28 '16 at 07:12

2 Answers2

4

You should use get method:

arraylist.get(arraylist.size() - 1);

This will return the object at the last location in your arraylist.

Be warned if you have an empty arraylist this will throw an error. You should check if list is empty first:

if(arraylist.size() > 0)
{
   arraylist.get(arraylist.size() - 1);
}
brso05
  • 13,142
  • 2
  • 21
  • 40
1

Just with:

arraylist.get(arraylist.size() -1 )
Nicolas Albert
  • 2,586
  • 1
  • 16
  • 16
  • 3
    You haven't consider the case if the list is empty ... – StackFlowed Nov 13 '14 at 21:07
  • @StackFlowed yeah, but what are you going to do if it's empty, since there's no value to return? The correct action depends on the application, and throwing an exception may be perfectly fine in many instances. – ajb Nov 13 '14 at 21:19