beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to get the last element of Arraylist?

By Chaitanya Singh | Filed Under: Java Collections

There are times when we need to get the last element of an ArrayList, this gets difficult when we don’t know the last index of the list. In this tutorial we are going to see an example to get the last element from ArrayList.

Example: Getting the last element from List

import java.util.ArrayList;
import java.util.List;
public class ArrayListExample {

  public static void main(String[] args) {
 
     /* Creating ArrayList of Strings and adding
      * elements to it
      */
     List<String> al = new ArrayList<String>();
     al.add("Ajay");
     al.add("Becky");
     al.add("Chaitanya");
     al.add("Dimple");
     al.add("Rock");
 
     // Displaying ArrayList elements
     System.out.println("ArrayList contains: "+al);
 
     // Logic to get the last element from ArrayList
     if (al != null && !al.isEmpty()) {
        System.out.println("Last element is:");
        System.out.println(al.get(al.size()-1));
     }
  }
}

Output:

ArrayList contains: [Ajay, Becky, Chaitanya, Dimple, Rock]
Last element is:
Rock

Enjoyed this post? Try these related posts

  1. Difference between ArrayList and HashMap in Java
  2. Java ArrayList addAll(int index, Collection c) Method example
  3. Java – Remove mapping from HashMap example
  4. HashSet Class in Java with example
  5. Check key & Value existence in Hashtable example – Java
  6. How to sort HashMap in Java by Keys and Values

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap