Skip to main content

ArrayList in Java

ArrayList in Java

In this article, we are going to discuss ArrayList in Java. ArrayList is a class from the Java Collection Framework and widely in our programs. We use ArrayList as a substitute for the array. So, it is important to know ArrayList in detail. We are going to see what is ArrayList in Java, how we can create the instance of ArrayList and the methods provided by the ArrayList in Java.

If you already familiar to ArrayList, you may learn common programs related to ArrayList.


What is ArrayList in Java?

ArrayList in Java is a List in which we can store and retrieve elements like an array but it provides a facility of Dynamic array or Resize-able Array i.e., An array which can grow and shrink its size at the time of addition or deletion of elements.
ArrayList is the part of Java Collection Framework. It is defined in java.util package and implements List interface which provide functionalities to perform basic operation like store, retrieve data from the list and etc.

Important point to remember about the ArrayList in Java

  • ArrayList is a Collection because ArrayList implements List interface and List interface extends Collection interface
  • ArrayList add elements at the next available index.
  • ArrayList can store one or more null values.
  • ArrayList maintains insertion order.
  • ArrayList allow to store duplicate objects.
  • ArrayList is a Generic-based Class i.e., we can set which type of elements going to stored into the List. By default type of arraylist is Object.
  • ArrayList store elements like an array, so we can access any elements randomly by using its index value.
  • ArrayList is not synchronized among the threads, we have to make ArrayList synchronized externally. Read this to know: How to synchronize ArrayList in Java

Hierarchy of the ArrayList in java?

Declaration of ArrayList
public class ArrayList<E>
    extends AbstractList<E>
    implements List<E>, Cloneable, java.io.Serializable {
     ----------------
}

AbstractList<E>

The AbstractList<E> provides a basic and abstract implementation of the List Interface to the ArrayList. Also, AbstractList<E> extends the AbstractCollection<E> which provides the abstract implementation of the Collection Interface.

Why Cloneable?

Cloneable is a marker interface and it is a part of java.lang package. A class implements this interface if it wants to call the clone() method of Object class using super keyword i.e., super.clone(); through any method or any constructor. If that class does not implement this marker interface and invoke the i.e., super.clone(); then java.lang.CloneNotSupportedExceptionwill be raised.
ArrayList in Java, provides overrode clone() method that internally calls the actual clone() method of Object class. So, ArrayList needs to implement this marker interface.
Note : The clone() method of Object class is used to create a cloned object.

Why Serializable?

Serializable is a marker interface and it is a part of java.io package. If Any class implements this interface then the class can be serialized or deserialized. Serialization is a process in which an object is converted into the byte stream and Deserialization is the reverse of serialization i.e., byte stream to java object. Serialization helps us to store and retrieve objects from and to files, databases, networks, etc. The only class marked with the Serializable interface can be serialized or deserialized.
ArrayList in Java often needs to store and retrieve the object from the files, databases, etc. That's why ArrayList is implemented as Serializable.

How to create objects of ArrayList in Java?

Above we have learned what is ArrayList in Java and its hierarchy. Now, let's have a look at the different ways to create objects of ArrayList. Learn Different ways to initialize ArrayList in Java.

Default Constructor :

ArrayList<String> books = new ArrayList<String>();
Here, the ArrayList is instantiated using the default constructor and the type of ArrayList is declared as the "String".

Using Constructor which require another Collection :

An ArrayList in Java can be created from another Collection and Collection can be a List, Set, etc.
ArrayList<String> books = new ArrayList<String>();
books.add("Programming In Java");
books.add("Learn ReactJs");
books.add("Introduction to Algorithms");
books.add("Data Structures");
ArrayList<String> copyBooks = new ArrayList<String>(books);
System.out.println(copyBooks);
Output
[Programming In Java, Learn ReactJs, Introduction to Algorithms, Data Structures]
Here, the ArrayList is instantiated using another Collection, that's why it is also known as Copy constructor.

How to create an ArrayList of Custom Objects?

To create an ArrayList of the Custom object, we first need to implement the structure of Custom Object.
class Book{
     private String name;
     private int price;

     public Book(String name, int price){
          this.name = name;
          this.price = price;
     }

     public String getName() {
          return name;
     }

     public void setName(String name) {
          this.name = name;
     }

     public int getPrice() {
          return price;
     }

     public void setPrice(int price) {
          this.price = price;
     }

     @Override
     public String toString(){  
          return "[ " + name + " : " + price + " ]";
     }   
}
Here, a model of Book class is implemented to use further in the article. Now let's create a list of books.
Book book1 = new Book("Programming In Java" , 450);
Book book2 = new Book("Learn ReactJs" , 350);
Book book3 = new Book("Introduction to Algorithms" , 600);
Book book4 = new Book("Data Structures" , 300);

ArrayList<Book> books = new ArrayList<Book>();
books.add(book1);
books.add(book2);
books.add(book3);
books.add(book4);
Above created ArrayList i.e., "books" is used further in the article for reference.

How to iterate ArrayList in Java?

In java, there exists number of approaches to iterate ArrayList in Java. Let's look at a few of them which come in day-to-day programming practices. Read complete article of Different ways to iterate ArrayList in Java

Using for-each loop

Java ArrayList Example 1: Iterate the ArrayList using for each loop and print all the books

for(Book book : books) {
      System.out.println(book); 
      /* 
       * toString() method of Book class invoked internally 
       * by println() method.
       */
}
Output
[ Programming In Java : 450 ]
[ Learn ReactJs : 350 ]
[ Introduction to Algorithms : 600 ]
[ Data Structures : 300 ]

Using Iterators

Java ArrayList Example 2: Iterate the ArrayList using iterators and print all the books

Iterator<Book> iterator = books.iterator();
while(iterator.hasNext()){
      Book book = iterator.next();
      System.out.println(book);
}
Output
[ Programming In Java : 450 ]
[ Learn ReactJs : 350 ]
[ Introduction to Algorithms : 600 ]
[ Data Structures : 300 ]

Using forEach() method

Java ArrayList Example 3: Iterate the ArrayList using forEach() method and print all the books

books.forEach(book -> System.out.println(book));
Output
[ Programming In Java : 450 ]
[ Learn ReactJs : 350 ]
[ Introduction to Algorithms : 600 ]
[ Data Structures : 300 ]

How to get the elements by index from ArrayList in Java?

The get() method returns the element from the ArrayList at the specified index.
Syntax
E value = arrayList.get(index);
/*
 * Here, 
 * E : The type of data objects stored into the ArrayList in Java.
 * index : index of the value in the ArrayList in Java
 */
Note : The ArrayList in Java follows 0-Based Indexing i.e., 0th index value is refer to 1st element of the ArrayList.

Java ArrayList Example 4: Get the 3rd book from the the "books" (ArrayList) using get() method

Book book = books.get(2);
System.out.println(book);
Output
[ Introduction to Algorithms : 600 ]
Note : The index value must be less than the size of ArrayList in Java (i.e., the number of elements stored in the ArrayList) otherwise java.lang.IndexOutOfBoundsException would be raised.

Java ArrayList Example 5: Trying to use index beyond the size of ArrayList using get() method

Book book = books.get(6); // Exception Occured
System.out.println(book);
Output
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 6, Size: 4
      at java.util.ArrayList.rangeCheck(ArrayList.java:657)
      at java.util.ArrayList.get(ArrayList.java:433)
      at prac.code.ArrayListExample.main(ArrayListExample.java:172)

How to check whether an elements is stored in the ArrayList in Java?

To check whether an elements is present into the ArrayList or not, ArrayList provides a method called contains(). This method takes an argument and compare each element of the ArrayList with equals() method and returns true if any time equals() method returns true.
Syntax
boolean result = arrayList.contains(object);

Java ArrayList Example 6: To check whether a given book is present in the ArrayList or not (Attempt 1)

Book book5 = new Book("Programming In Java" , 450); // Same as book1
if(books.contains(book5)) {
       System.out.println(book5.getName() + " is present in the list");
} else {
       System.out.println(book5.getName() + " is not present in the list");
}
Output
Programming In Java is not present in the list
Yes, the output is saying the book is not present in the list because the "book5" is a new book even though the name and price are same as "book1" but still it is considered as a new book to the ArrayList. It is because the comparison is done by using the equals() method provided by the Object class which compares two objects that are the same or not but doesn't compare the data of the objects.
To make the comparison based on the data, we need to Override the functionality of the equals() method in the Book class. Lets first override the equals() method in the Book class.
class Book{
     /* ----------
      * ----------
      * field and other methods
      * of the Book class
      * ----------
      */
      
      @Override
      public boolean equals(Object obj) {
           Book book = (Book) obj;
           return name.equals(book.getName()) 
                      && price == book.getPrice();
      }
}

Java ArrayList Example 7: To check whether a given book is present in the ArrayList or not (Attempt 2)

Book book5 = new Book("Programming In Java" , 450); // Same as book1
if(books.contains(book5)) {
       System.out.println(book5.getName() + " is present in the list");
} else {
       System.out.println(book5.getName() + " is not present in the list");
}
Output
Programming In Java is present in the list

How to remove elements from the ArrayList in Java?

If you want to remove duplicates from ArrayList, read this article: How to remove duplicates from ArrayList in Java

Using remove(index) method

The remove(index) method is used to remove element from the ArrayList on the basis of specified index location. This method takes an index as an argument and remove that element from the ArrayList and shift all the elements to the left side of the list by 1 position and return the removed element.

Java ArrayList Example 8: Remove the second book from the ArrayList

ArrayList<Book> newBookList = new ArrayList<Book>(books);

System.out.println("-------ArrayList : Before removing second book--------");
newBookList.forEach(b -> System.out.println(b));

Book book = newBookList.remove(1);

System.out.println("-------ArrayList : After removing second book---------");
newBookList.forEach(b -> System.out.println(b));

System.out.println("Removed Book : " + book);
Output
-------ArrayList : Before removing second book--------
[ Programming In Java : 450 ]
[ Learn ReactJs : 350 ]
[ Introduction to Algorithms : 600 ]
[ Data Structures : 300 ]
-------ArrayList : After removing second book---------
[ Programming In Java : 450 ]
[ Introduction to Algorithms : 600 ]
[ Data Structures : 300 ]
Removed Book : [ Learn ReactJs : 350 ]
Note : Similar to get() method, the index value must be less than the size of ArrayList in Java (i.e., the number of elements stored in the ArrayList) otherwise java.lang.IndexOutOfBoundsException would be raised.

Using remove(object) method

The remove(object) method is used to remove the provided object (into the argument of remove() method) from the ArrayList in Java. The provided element in the argument say "object" is compared with each element of the ArrayList say "obj" by equals() method i.e., object.equals(obj) and whenever it returns true then the object is removed from the ArrayList.
After the removing elements, all the remaining elements shift to the left to fill the empty space.

Java ArrayList Example 9: Remove the "Learn ReactJs" book from the ArrayList

ArrayList<Book> newBookList = new ArrayList<Book>(books);

System.out.println("-------ArrayList : Before removing second book--------");
newBookList.forEach(b -> System.out.println(b));

Book removeBook = new Book("Learn ReactJs" , 350);
boolean removed = newBookList.remove(removeBook);

System.out.println("-------ArrayList : After removing second book---------");
newBookList.forEach(b -> System.out.println(b));

if (removed) {
      System.out.println("Removed Book : " + removeBook)
}
Output
-------ArrayList : Before removing second book--------
[ Programming In Java : 450 ]
[ Learn ReactJs : 350 ]
[ Introduction to Algorithms : 600 ]
[ Data Structures : 300 ]
-------ArrayList : After removing second book---------
[ Programming In Java : 450 ]
[ Introduction to Algorithms : 600 ]
[ Data Structures : 300 ]
Removed Book : [ Learn ReactJs : 350 ]

Using removeIf() method

To remove object on the basis of some conditions we can use removeIf() method. The removeIf() method takes an argument of java.util.Predicate type, apply that predicate to each element of ArrayList and remove all those element which satisfies the given predicate.
After the removing elements, all the remaining elements shift to the left to fill the empty space.

Java ArrayList Example 10: Remove the all the books from the ArrayList whose price is above 500

ArrayList<Book> newBookList = new ArrayList<Book>(books);

System.out.println("-------ArrayList : Before--------");
newBookList.forEach(b -> System.out.println(b));

newBookList.removeIf(b -> b.getPrice() > 500);

System.out.println("-------ArrayList : After---------");
v.forEach(b -> System.out.println(b));
Output
-------ArrayList : Before--------
[ Programming In Java : 450 ]
[ Learn ReactJs : 350 ]
[ Introduction to Algorithms : 600 ]
[ Data Structures : 300 ]
-------ArrayList : After---------
[ Programming In Java : 450 ]
[ Learn ReactJs : 350 ]
[ Data Structures : 300 ]
Note : The "b -> b.getPrice() > 500" is the lambda representation of the Predicate class. Predicate is a Functional Interface which in introduced in Java 8. To know more about the Function interface and Lambda Expression read these article : Functional Interface in Java and Lambda Expression in Java.

Few more methods of ArrayList in Java?

size() : This method returns the size of ArrayList in Java i.e., how many elements are stored in the ArrayList
clear() : This method removes all elements from the ArrayList and make it empty.
isEmpty() : This method returns true if the ArrayList is not containing any elements in it otherwise false

Java ArrayList Example 11: Different States of ArrayList in Java

System.out.println("How many are there in the List? : " + books.size());

System.out.println("Removing all elements from the ArrayList.....");
books.clear();

if(books.isEmpty()) {
       System.out.println("List is Empty Now");
}
Output
How many are there in the List? : 4
Removing all elements from the ArrayList.....
List is Empty Now

Related Posts:


Conclusion

In this article, we have learned what is ArrayList in Java, how we can create an instance of ArrayList and the related methods of ArrayList. ArrayList in Java is a widely used class, due to its capability of resizing its array size.

Comments

Post a Comment

Popular posts from this blog

How HashMap works internally in java

How Hashmap works Internally in Java In this article, we are going to see how HashMap internally works in java. Also, we will have a look at what Java 8 made changes on the internal working of Hashmap to make it faster. What is Hashmap and Hashing in java? How Hashmap works Internally in Java is majorly dependent upon the Hashing Principle. So, Before going to learn how HashMap works internally in java, lets first understand what is HashMap and hashing. HashMap : A HashMap is a map used to store mappings of key-value pairs. Also, it works on the Principle of Hashing. To know more about the HashMap, visit this article: HashMap in Java Hashing Principle : Simply, Hashing is a method used to produce an integer value from an object and this integer value known as the hash value. In HashMap, the key object is used for Hashing.
Internal Struture of the HashMap in java For internal working of HashMap, HashMap maintains an array of bucket, each bucket is a linked-list and linked list is a li…

HashMap in Java

HashMap in Java In this article, we are going to learn about the most important class of Java known as HashMap. HashMap in java is the most used map interface and it is used in our regular or day-to-day programming practices.
What is HashMap in java? Lets first start with basic definition of HashMap,
HashMap is a map which store key-value pair, where each key is mapped with a value.
HashMap defined in java.util package and implements map interface which provides functionalities to perform basic operation like store, retrieve, size of the map etc. It is a part of Java Collection Framework. Time complexity of HashMap in Java? : Time complexity to store and retrieve data from the HashMap is O(1) in the Best Case. But it can be O(n) in the worst case and after the changes made in Java 8 the worst case time complexity can be O(log n) atmost. Internal working of HashMap in java HashMap maintains an array of the buckets, where each bucket is a linked-list and the linked list is a list of…