For enquiries call:

Phone

+1-469-442-0620

HomeBlogProgrammingArrayList in Java With Examples 

ArrayList in Java With Examples 

Published
05th Sep, 2023
Views
view count loader
Read it in
8 Mins
In this article
    ArrayList in Java With Examples 

    The Collection framework of Java plays an important role in the Java language. In the Collection framework, we have different types of classes and interfaces. It provides an architecture to store and manipulate objects or data. It allows us to perform all operations like searching, sorting, deletion, addition, and manipulation of the data or objects. To know and learn more about Java you can go for the best Programming courses and grow with mentorship programs. 

    What is an ArrayList in Java?

    An ArrayList is a class in the Java collection framework. ArrayList uses a dynamic array for storing the elements. ArrayList in java 8 and old versions is also same as an Array, but in an array, the size is fixed, whereas in ArrayList there is no size limit. ArrayList is found in java.util package. It is like the Vector class of C++.

    The characteristic of ArrayList can be defined as ArrayList can have duplicate elements. It internally implements the List interface so we can make use of all the methods defined in the List interface. Also, the ArrayList maintains the insertion order internally. Also, we can say java arrayList of objects, Java Programming for beginners provides best way of understanding the courses by providing in-depth knowledge on each topic.

    How do you Create ArrayList in Java?

    Java Collection framework was non generic till JDK 1.5 and after 1.5 generics was introduced. The generic allows you to have only one type of object in a Collection. Below examples shows how to declare an arrayList in java using both Generic and Non generic types

    ArrayList list=new ArrayList(); // non-generic arraylist
    ArrayList<> list=new ArrayList<>(); // generic arraylist

    How to Work with ArrayList?

    Before using the functionality of ArrayList, first understand how ArrayList works? how it is internally implemented? what are all the methods an ArrayList class provides? So it will be easier to understand while writing code using ArrayList. Before that we have to import arrayList java in the class.

    import java.util.*; 
    public class ArrayListExample{
    public static void main(String[] args){
    ArrayList<> list = new ArrayList<>();
                            list.add(“Fruits”);
                            list.add(“Vegetables”);
                            list.add(“Beverages”);
                            list.add(“Snacks”);
                            list.add(“Juices”);
    System.out.println(“Print all data from the list ”+list);
    }
    }

    In the above example as you can see, we have created a class with name ArrayListExample, and we have created a generic ArrayList for that and we have added values and printing all the values using print statement.

    How to Add, Remove and Modify Elements?

    In ArrayList the manipulation of bulk data is easy and understandable. In the below example program, it is mentioned on how to add, remove and modify the elements using ArrayList.

    public class ArrayListExample {
                public static void main(String[] args){
    ArrayList<> list = new ArrayList<>();
                            list.add(“Fruits”);
                            list.add(“Vegetables”);
                            list.add(“Beverages”);
                            list.add(“Snacks”);
                            list.add(“Juices”);
    System.out.println(“Print all initial list of Array elements ”+list);
                list.remove(“Beverages”);
    System.out.println(“After calling remove method, the list of Array elements = ”+list);
    list.remove(1);
    System.out.println(“After calling remove method using particular index, the list of Array elements = ”+list);
    //Creating another ArrayList
    ArrayList<> list2 = new ArrayList<>(); 
         list2.add("Ravi"); 
       list2.add("Hanumat"); 
     //Adding new elements to arraylist 
      list.addAll(list2); 
     System.out.println("Updated list : "+list); 
     //Removing all the new elements from arraylist 
      list.removeAll(list2); 
     System.out.println("After invoking removeAll() method: "+list); 
     //Removing elements on the basis of specified condition 
     list.removeIf(str -> str.contains("Fruits")); //Here, we are using Lambda expression 
     System.out.println("After invoking removeIf() method: "+list); 
     //Removing all the elements available in the list 
     list.clear(); 
     System.out.println("After invoking clear() method: "+list); 
    }
    }

    How to Access Items of ArrayList?

    To access the items of ArrayList, we can get the values based on the index using java arrayList get() method provided by the ArrayList class. 

    import java.util.*; 
    public class ArrayListExample4{ 
               public static void main(String args[]){ 
                                 ArrayList<> list = new ArrayList<>(); 
                           list.add("Mango"); 
                            list.add("Apple"); 
                            list.add("Banana"); 
     list.add("Grapes"); 
     //accessing the element 
     System.out.println("Returning element: "+ list.get(1));//it will return the 2nd element, because index starts from 0 
     //changing the element 
     list.set(1,"Dates"); 
     //Traversing list 
     for(String fruit: list) 
     System.out.println(fruit); 
     } 
    } 

    How to Find the Size of An ArrayList?

    ArrayList class provides an inbuilt method to get the size of the ArrayList. In the example given below we have used size function to get the size of the ArrayList.

    import java.util.*;  
    class ArrayList4{  
    publicstaticvoid main(String args[]){  
        ArrayList<> list=new ArrayList<>();//Creating new arraylist in java
               list.add("Ravi");//Adding object in arraylist
               list.add("Vijay");  
               list.add("Ravi");  
               list.add("Ajay");  
               System.out.println("Get the size of the array list :"+list.size());  
    }
    }

    How to Iterate Through an ArrayList?

    In Collection framework, we can loop arraylist java using the 6 ways.

    1. By Iterator interface.
    2. By for-each loop.
    3. By ListIterator interface.
    4. By for loop.
    5. By forEach() arraylist method in java.
    6. By forEachRemaining() method.

    In the below example, we can find the different ways of iterating the elements

    import java.util.*;  
    publicclass ArrayListExample2{  
    publicstaticvoid main(String args[]){  
      ArrayList<> list=new ArrayList<>();//Creating arraylist
      list.add("Mango");//Adding object in arraylist  
      list.add("Apple");    
      list.add("Banana");    
      list.add("Grapes");    
    //Traversing list through Iterator
      Iterator itr=list.iterator();//getting the Iterator
    while(itr.hasNext()){//check if iterator has the elements
       System.out.println(itr.next());//printing the element and move to next
      }  
    //Traversing list through for-each loop
    for(String fruit:list)    
        System.out.println(fruit);  
    
    
     System.out.println("Traversing list through List Iterator:");  
    //Here, element iterates in reverse order
                  ListIterator<> list1=list.listIterator(list.size());  
    while(list1.hasPrevious())  
                  {  
                      String str=list1.previous();  
                      System.out.println(str);  
                  }  
            System.out.println("Traversing list through for loop:");  
    for(int i=0;i<list.size();i++)  
               {  
                System.out.println(list.get(i));     
    }  
            System.out.println("Traversing list through forEach() method:");  
    //The forEach() method is a new feature, introduced in Java 8.
            list.forEach(a->{ //Here, we are using lambda expression
                  System.out.println(a);  
                  });  
                System.out.println("Traversing list through forEachRemaining() method:");  
                  Iterator<> itr=list.iterator();  
                  itr.forEachRemaining(a-> //Here, we are using lambda expression
                  {  
                System.out.println(a);  
                  });  
     }  
    }  

    How to Sort an ArrayList?

    In java, the Collections class provides inbuilt methods to sort the elements. The collections class provides sort() method that is Collections.sort(), using which we can easily sort the elements.

    import java.util.*;  
    class SortArrayList{  
    publicstaticvoid main(String args[]){  
    //Creating a list of fruits
      List<> list1=new ArrayList<>();  
      list1.add("Mango");  
      list1.add("Apple");  
      list1.add("Banana");  
      list1.add("Grapes");  
    //Sorting the list
      Collections.sort(list1);  
    //Traversing list through the for-each loop
    for(String fruit:list1)  
        System.out.println(fruit);  
     System.out.println("Sorting numbers...");  
    //Creating a list of numbers
      List<> list2=new ArrayList<>();  
      list2.add(21);  
      list2.add(11);  
    //Sorting the list
      Collections.sort(list2);  
    //Traversing list through the for-each loop
    for(Integer number:list2)  
        System.out.println(number);  
     }     
    }  

    ArrayList Example in Java

    ArrayList in Java example:

    import java.util.*;  
    publicclass ArrayListExample1{  
    publicstaticvoid main(String args[]){  
      ArrayList<> list=new ArrayList<>();//Creating arraylist  
          list.add("Mango");//Adding object in arraylist  
          list.add("Apple");    
          list.add("Banana");     
    //Printing the arraylist object 
          System.out.println(list);  
     }  
    }  

    All Methods of ArrayList in Java

    Some of the ArrayList methods in java which we can use in the manipulation of elements are listed below:

    MethodDescription
    void add(int index, E element)Java arrayList add method is used to insert the specified element at the specified position in a list.
    boolean add(E e)ArrayList in java add() method is used to append the specified element at the end of a list.
    boolean addAll(Collection<? extends E> c)It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator.
    boolean isEmpty()It returns true if the list is empty, otherwise false.
    boolean remove(Object o)The  java arrayList remove() method is  used to remove the first occurrence of the specified element.
    boolean removeIf(Predicate<? super E> filter)arrayList in java remove used to remove all the elements from the list that satisfies the given predicate.
    void sort(Comparator<? super E> c)It is used to sort the elements of the list on the basis of the specified comparator.

    Difference Between an ArrayList and an Array in Java

    The difference between Array and arrayList in java is listed below:

    Array
    ArrayList
    An Array is dynamically created object, it acts as container, holds the constant number of values
    ArrayList is a class of Collection framework of java.
    Array is static in size
    ArrayList is dynamic in size
    Array is fixed in length
    ArrayList is variable in length
    It is mandatory to provide the size of the array
    We can create ArrayList in java without specifying the size or length
    We cannot use generic in arrays
    We can use generics in ArrayList
    Array can be multi-dimensional
    ArrayList is always single dimensional
    We can use for loop and for each loop to iterate the elements
    We can use an iterator to iterate over arrayList

    Conclusion

    Through this article we know that the ArrayList is part of Collection framework. It inherits the AbstractList class and implements the List interface. Also, ArrayList is the implementation of a dynamic array. Operations that can be performed in ArrayList are Adding, removing, iterating, and sorting. We can also convert arrayList to array and array to ArrayList in Java using the specified functions. If you are planning to learn any new languages, you can learn Python Programming to understand the concepts easily and get hands-on practice.

    Frequently Asked Questions (FAQs)

    1Can an ArrayList hold different types of objects in Java?

    Before introducing generics arraylist can hold different types of objects, but after the introduction of generic, we cannot use different types of objects in java.

    2Can you remove multiple elements from an ArrayList at once in Java?

    Yes, we can remove multiple elements from an ArrayList in java at once, using the removeAll() method.

    3Can you sort an ArrayList in Java?

    Yes, we can sort an arrayList in java. the Collections class provides the inbuilt methods to sort the elements. The collections class provides sort() method that is Collections.sort(), using which we can easily sort the elements.

    4Can an ArrayList contain duplicate elements in Java?

    Yes, in Arraylist it will not check the duplication of elements, that means we can add any number of repeated values to ArrayList.

    Profile

    Anusha SP

    Author

    Senior Software Engineer, with good hands-on experience and knowledge on Tech stacks and Project Management. I’m a technical blogger and content writer. Like to involve myself in learning and upgrading myself in the activities where I can contribute.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Programming Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon