Custom ArrayList in Java
In Java, array and ArrayList are the well-known data structures. An array is a basic functionality provided by Java, whereas ArrayList is a class of Java Collections framework. It belongs to java.util package. The limitation of the ArrayList is that it allows us to store data of the same data type. To overcome this problem, we can customize the ArrayList and can store data of different primitive types. In this section, we are going to learn custom ArrayList in Java and how to implement custom ArrayList in Java. Before moving to the custom ArrayList, let's have a look at ArrayList in Java.
Java ArrayList Class
In Java, ArrayList is a class of Java Collections framework. It implements List<E>, Collection<E>, Iterable<E>, Cloneable, Serializable, and RandomAccess interfaces. It extends the AbstractList<E> class. It uses a dynamic array for storing the elements.
We can create an instance of ArrayList by using the following statement:
ArrayList is internally backed by the array in Java. The resize operation in ArrayList slows down the performance as it involves a new array and copying content from an old array to a new array. It calls the native implemented method System.arraycopy(sec, srcPos, dest, destPos, length).
We cannot store primitive type in ArrayList. So, it stores only objects. It automatically converts primitive type to object. For example, we have created an ArrayList object:
The JVM converts it into Integer object through auto-boxing.
Custom ArrayList in Java
A list that contains more than one type of data (elements) is known as custom ArrayList. It is based on user requirements. In the custom ArrayList, the data is provided by the custom inner class that is formed by a combination of various primitive object datatypes.
Consider a situation, if we want to take input of product detail. The detail includes pid, pname, pavailability, pprice, prating. Typically to input these attributes in the ArrayList, we need to create a separate ArrayList for each attribute, as follows:
The above process is lengthy and takes lots of time to input the elements. It uses separate ArrayList to store each attribute. To overcome the problem, we use custom ArrayList. It stores more than one data type in a single ArrayList. For example, consider the following figure:
In the above figure, we have created an ArrayList. In all the indices of ArrayList, we have stored different data such as accno, name, and interest.
Implementation of Custom ArrayList in Java
To implement the custom ArrayList in Java, follow the steps given below:
Let's follow the above steps and implement the custom ArrayList.
Example of Custom ArrayList
Next TopicArrayList vs HashMap