The following is part of the List interface (which ArrayList implements):
E e = list.get(list.size() - 1);
E is the element type. If the list is empty, get throws an IndexOutOfBoundsException. You can find the whole API documentation here.
The following is part of the List interface (which ArrayList implements):
E e = list.get(list.size() - 1);
E is the element type. If the list is empty, get throws an IndexOutOfBoundsException. You can find the whole API documentation here.
There isn't an elegant way in vanilla Java prior to Java 21.
Google Guava
The Google Guava library is great - check out their Iterables.getLast() method. This method will throw a NoSuchElementException if the list is empty, as opposed to an IndexOutOfBoundsException, as with the typical size()-1 approach - I find a NoSuchElementException much nicer, or the ability to specify a default:
lastElement = Iterables.getLast(iterableList);
You can also provide a default value if the list is empty, instead of an exception:
lastElement = Iterables.getLast(iterableList, null);
or, if you're using Options:
lastElementRaw = Iterables.getLast(iterableList, null);
lastElement = (lastElementRaw == null) ? Option.none() : Option.some(lastElementRaw);
java - Get last added element Arraylist - Stack Overflow
java - Get last element in arraylist - Stack Overflow
6.1.8 LAST ELEMENT IN ARRAY
Last item in c#
Yes, as the other people said, ArrayList preserves insert order. If you want the last added element, (only if you always add your elements with add(element)) just type this:
yourArrayList.get(yourArrayList.size()-1);
Your answer is in the link that you said :)
Yes for ArrayList, It preserves the order of insertion
If you explicitly add the element at particular position by specifying index add(), in this case you need to set insertion time by customizing ArrayList implementation and while retrieving the latest inserted element consider that time in calculation
or better have a reference pointing to last inserted item as Marko Topolnik suggested, also maintain it on removal
Better thing would be use LinkedHashSet, if you are not concerned about uniqueness property of set
You can make a control on the size of the arraylist, id est
if (arraylist.size()==1){
System.out.println("this is the last element in the arraylist");
}
and if you want to print the last element you can access it as (index=0 in case it is just one element)
arraylist.get(arraylist.size()-1);
This should do it I guess:
if (list.size() == 1) {
System.out.println(list.get(list.size() - 1)) // or just .get(0) of course...
} else {
System.out.println("List is empty or bigger than one")
}