Before proceeding further let us quickly revise the concept of the arrays and ArrayList quickly. So in java, we have seen arrays are linear data structures providing functionality to add elements in a continuous manner in memory address space whereas ArrayList is a class belonging to the Collection framework. Being a good programmer one is already aware of using ArrayList over arrays despite knowing the differences between these two. Now moving ahead even with ArrayList there comes a functionality to pass the type of datatype of elements that are supposed to be stored in the ArrayList be it an object, string, integer, double, float, etc.
Syntax:
Arraylist<DataType> al = new ArrayList<Datatype> ;
Note: ArrayList in Java (equivalent to vector in C++) having dynamic size. It can be shrunk or expanded based on size. ArrayList is a part of the collection framework and is present in java.util package.
Syntax:
ArrayList <E> list = new ArrayList <> ();
The important thing here out is that E here represents an object datatype imagine be it Integer here. The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int. Do go through the concept of wrapper classes in java before moving forward as it will serve here at the backend making understanding clearer if we are well aware of autoboxing and unboxing concepts. It is because while performing operations over elements in list their syntax will differ so do grasping over concept will deplete as suppose consider a scenario of adding elements to custom ArrayList and note the differences in syntax between two of them.
Syntax:
ArrayList<Integer> al = new Arraylist<Integer>() ;
al.add(1) ;
Syntax:
ArrayList alobj = new Arraylist() ;
alobj(new Integer(1)) ;
Let us take a sample illustration to perceive as provided below as follows:
Illustration:

here we are having all the elements of the same type which in general we often do use. Now let us propose the same diagrammatic flow ArrayList simply supports multiple data in the way shown in this image.

In the above ArrayList, we can clearly see that the elements been stored in are of different types. So it does erupt out the concept of restricting. to a single type and not only this List do go gives us the flexibility to make List as per our type where we have access to what kind of data types can be there in our ArrayList. This List is referred to as Custom ArrayList in java. A custom ArrayList has attributes based on user requirements and can have more than one type of data. This data is provided by a custom inner class which is formed by the combination of various primitive object datatypes.
Implementation: Consider a case when we have to take input as N number of students and details are:
- roll number
- name
- marks
- phone number
Suppose if we are unaware of the concept of custom Arraylist in java then we would be making below listed individual ArrayLists. As we define 4 ArrayLists and save data accordingly in each of them.
ArrayList<Integer> roll = new ArrayList<>(); // roll number
ArrayList<String> name = new ArrayList<>(); // name
ArrayList<Integer> marks = new ArrayList<>(); // marks
ArrayList<Long> phone = new ArrayList<>(); // phone number
Now we would be iterating over each of them to fetch student data increasing the time complexity of our program to a greater extent as illustrated below as follows.
for (int i = 0; i < n; i++)
{
// Adding all the values to each arraylist
// each arraylist has primitive datatypes
roll.add(rollnum_i);
name.add(name_i);
marks.add(marks_i);
phone.add(phone_i);
}
Now let us do the same with the help of the concept learned above by implementing the same. So in order to construct our custom ArrayList perform the below-listed steps as follows:
Procedure: Constructing custom ArrayList are as follows:
- Build an ArrayList Object and place its type as a Class Data.
- Define a class and put the required entities in the constructor.
- Link those entities to global variables.
- Data received from the ArrayList is of that class type that stores multiple data.
Example
Java
// Java program to illustrate Custom ArrayList
// Importing ArrayList class from java.util package
import java.util.ArrayList;
// Class 1
// Outer class
// Main class
// CustomArrayList
class Data {
// Global variables of the class
int roll;
String name;
int marks;
long phone;
// Constructor has type of data that is required
Data(int roll, String name, int marks, long phone)
{
// Initialize the input variable from main
// function to the global variable of the class
// this keyword refers to current instance
this.roll = roll;
this.name = name;
this.marks = marks;
this.phone = phone;
}
}
public class GFG {
// Custom class which has data type class has
// defined the type of data ArrayList
// size of input 4
int n = 4;
// Class 2
// Inner class
// The custom datatype class
public void addValues(int roll[], String name[],
int marks[], long phone[])
{
// local custom arraylist of data type
// Data having (int, String, int, long) type
// from the class
ArrayList<Data> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
// create an object and send values to the
// constructor to be saved in the Data class
list.add(new Data(roll[i], name[i], marks[i],
phone[i]));
}
// after adding values printing the values to
// test the custom arraylist
printValues(list);
}
// Method 2
// To print the values
public void printValues(ArrayList<Data> list)
{
// list- the custom arraylist is sent from
// previous function
for (int i = 0; i < n; i++) {
// Data received from arraylist is of Data
// type which is custom (int, String, int,
// long) based on class Data
Data data = list.get(i);
// Print and display custom ArrayList
// elements that holds for student attribute
// Data variable of type Data has four
// primitive datatypes roll -int name-
// String marks- int phone- long
System.out.println(data.roll + " " + data.name
+ " " + data.marks + " "
+ data.phone);
}
}
// Method 1
// Main driver method
public static void main(String args[])
{
// Custom input data
int roll[] = { 1, 2, 3, 4 };
String name[]
= { "Shubham", "Atul", "Ayush", "Rupesh" };
int marks[] = { 100, 99, 93, 94 };
long phone[] = { 8762357381L, 8762357382L,
8762357383L, 8762357384L };
// Creating an object of the class
GFG custom = new GFG();
// Now calling function to add the values to the
// arraylist
custom.addValues(roll, name, marks, phone);
}
}
Output1 Shubham 100 8762357381
2 Atul 99 8762357382
3 Ayush 93 8762357383
4 Rupesh 94 8762357384
A custom ArrayList in Java can be created by extending the java.util.AbstractList class and implementing its methods. Here's an example of how you can create a custom ArrayList:
Java
import java.util.AbstractList;
import java.util.Arrays;
import java.util.List;
public class CustomArrayList<E> extends AbstractList<E> {
private int size = 0;
private static final int DEFAULT_CAPACITY = 10;
private Object elements[];
public CustomArrayList() {
elements = new Object[DEFAULT_CAPACITY];
}
public CustomArrayList(int capacity) {
elements = new Object[capacity];
}
@Override
public int size() {
return size;
}
@Override
public E get(int index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size " + index);
}
return (E) elements[index];
}
@Override
public void add(int index, E element) {
if (index > size || index < 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size " + index);
}
ensureCapacity();
for (int i = size - 1; i >= index; i--) {
elements[i + 1] = elements[i];
}
elements[index] = element;
size++;
}
@Override
public E remove(int index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size " + index);
}
Object item = elements[index];
for (int i = index; i < size - 1; i++) {
elements[i] = elements[i + 1];
}
size--;
return (E) item;
}
private void ensureCapacity() {
int newSize = elements.length * 2;
elements = Arrays.copyOf(elements, newSize);
}
public static void main(String[] args) {
List<Integer> list = new CustomArrayList<>();
list.add(1);
list.add(2);
list.add(3);
System.out.println("CustomArrayList: " + list);
}
}
OutputCustomArrayList: [1, 2, 3]
In this example, the custom ArrayList is created by extending the AbstractList class and implementing its methods size, get, add, and remove. The custom ArrayList also has a private method called ensureCapacity which doubles the size of the ArrayList if it runs out of space.
Advantages of using a custom ArrayList in Java:
- Flexibility: Creating a custom ArrayList allows you to customize the behavior of the ArrayList to meet the specific needs of your application.
- Understanding: Creating your own ArrayList from scratch can help you understand how ArrayLists work and how to use them effectively.
Disadvantages of using a custom ArrayList in Java:
- Time consumption: Creating a custom ArrayList can be time-consuming and requires a good
Similar Reads
Java List Interface
The List Interface in Java extends the Collection Interface and is a part of the java.util package. It is used to store the ordered collections of elements. In a Java List, we can organize and manage the data sequentially. Key Features:Maintained the order of elements in which they are added.Allows
15+ min read
AbstractList in Java with Examples
The AbstractList class in Java is a part of the Java Collection Framework and implements the Collection interface and the AbstractCollection class. AbstractList class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a Rand
7 min read
ArrayList in Java
Java ArrayList is a part of the collections framework and it is a class of java.util package. It provides us with dynamic-sized arrays in Java. The main advantage of ArrayList is that, unlike normal arrays, we don't need to mention the size when creating ArrayList. It automatically adjusts its capac
9 min read
LinkedList in Java
Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure, which is a linear data structure where the elements are not stored in contiguous locations, and every element is a separate object with a data part and an
12 min read
Immutable List in Java
ImmutableList, as suggested by the name, is a type of List which is immutable. It means that the content of the List are fixed or constant after declaration, that is, they are read-only. If any attempt made to add, delete and update elements in the List, UnsupportedOperationException is thrown. An I
5 min read
CopyOnWriteArrayList in Java
CopyOnWriteArrayList class is introduced in JDK 1.5, which implements the List interface. It is an enhanced version of ArrayList in which all modifications (add, set, remove, etc) are implemented by making a fresh copy. It is found in java.util.concurrent package. It is a data structure created to b
6 min read
Custom ArrayList in Java
Before proceeding further let us quickly revise the concept of the arrays and ArrayList quickly. So in java, we have seen arrays are linear data structures providing functionality to add elements in a continuous manner in memory address space whereas ArrayList is a class belonging to the Collection
8 min read
Difference Between Synchronized ArrayList and CopyOnWriteArrayList in Java Collection
As we know that the ArrayList is not synchronized, if multiple threads try to modify an ArrayList at the same time, then the final outcome will be non-deterministic. Hence synchronizing the ArrayList is a must to achieve thread safety in a multi-threaded environment. In order to make List objects we
6 min read
How to remove a SubList from a List in Java
Given a list in Java, the task is to remove all the elements in the sublist whose index is between fromIndex, inclusive, and toIndex, exclusive. The range of the index is defined by the user. Example: Input list = [1, 2, 3, 4, 5, 6, 7, 8], fromIndex = 2, endIndex = 4 Output [1, 2, 5, 6, 7, 8] Input
2 min read
Randomly Select Items from a List in Java
In this article, we will explore how to efficiently select an element from a list in Java. The basic approach involves generating a random index between 0 and the size of the list, and then using that index to retrieve the item. Different Ways to Select Items from a ListBelow are the different appro
3 min read