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
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to find length of ArrayList in Java

By Chaitanya Singh | Filed Under: Java Collections

By using  size() method of ArrayList class we can easily determine the size of the ArrayList. This method returns the number of elements of ArrayList.

public int size()

Example:

package beginnersbook.com;
import java.util.ArrayList;
public class Details
{
    public static void main(String [] args)
    {
        ArrayList<Integer> al=new ArrayList<Integer>();
        System.out.println("Initial size: "+al.size());
        al.add(1);
        al.add(13);
        al.add(45);
        al.add(44);
        al.add(99);
        System.out.println("Size after few additions: "+al.size());
        al.remove(1);
        al.remove(2);
        System.out.println("Size after remove operations: "+al.size());
        System.out.println("Final ArrayList: ");
        for(int num: al){
            System.out.println(num);
        }
   }
}

Output:

Initial size: 0
Size after few additions: 5
Size after remove operations: 3
Final ArrayList: 
1
45
99

Comments

  1. Vaibhav Chintawar says

    June 22, 2016 at 3:34 PM

    after removing al.remove(2); still why we are getting an output which is at 3rd position al.add(45)

    Reply
    • venkatesh says

      August 6, 2016 at 12:05 PM

      Because when we remove element at first index, the element 45 moves to index 1 and 44 moves to index 2.Now when we remove(2) 44 will be deleted.

      Reply

Leave a Reply Cancel reply

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

ArrayList Tutorial

  • Java ArrayList

Java ArrayList Methods

  • add(Object obj)
  • add(int index, Object element)
  • addAll(Collection c)
  • addAll(int index, Collection c)
  • contains()
  • get()
  • indexOf()
  • ensureCapacity()
  • isEmpty()
  • lastIndexOf()
  • remove()
  • remove(Object obj)
  • trimToSize()
  • set()
  • clone()
  • clear()
  • size()

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap