How to create Custom Java Collection by extending from an existing Collection class

Suresh Kumar
4 min readJul 16, 2020

--

Though Core Java provides a number of builtin Collections such as ArrayList, LinkedList, HashSet, etc…., sometimes it may be required to create a custom Collection.

This post briefs the steps(with an example) to create a Custom Java Collection class by extending from an existing Collection class. (There are other ways of creating Custom Collection classes which we will be exploring in my next posts.). (You can refer my Complete Core Java Course here , with 25 Hours of Video, reading material and source code examples)

1. Based on your requirement, try to find which of existing Collection class has characteristics similar to that of your requirement.

2. Now, create a custom Collection class by extending from this existing Collection class.

3. And then override few methods, so that required Customization can be achieved.

4. Perform Unit Test of this Custom Collection just developed.

Lets explore this by considering a simple requirement, to create a Custom List which can store upto two duplicates of an object, that means you will not be able to add same object third time.

Below are the steps and code snippets for the same.

Step 1. Create a class CustomArrayList by extending from ArrayList

Step 2. Add required constructors to CustomArrayList

Step 3. Override add() methods in CustomArrayList

Step 4. Override set() methods in CustomArrayList

Step 5. Test CustomArrayList

Java Custom Collection Classes

Below are details of each of above step

Step 1: Create a class CustomArrayList by extending from ArrayList

class MyCustomArrayList<T> extends ArrayList<T>{
private static final long serialVersionUID = 1L;
//add source code specified in below steps 2 to 4
}

Step 2: Add required constructors to CustomArrayList

public MyCustomArrayList(){}//overloaded constructors can be added, if required

Step 3: Override add() methods in CustomArrayList

Create a new private method which checks number of current occurrences of given object, and adds only if number of occurrences is less than 2

//method to add element at the end of the list
private boolean addElement(T obj)
{
boolean added = false;
int num_of_occurrences = Collections.frequency(this, obj);if(num_of_occurrences<2)
{
added = super.add(obj);
}

return added;
}
//method to add element at a specific index, of the list
private boolean addElement(int index, T obj)
{
boolean added = false;
int num_of_occurrences = Collections.frequency(this, obj);
if(num_of_occurrences<2)
{
super.add(index, obj);
}

return added;
}

Invoke above method from overloaded add methods, which need to be overridden.

@Override
public boolean add(T obj)
{
return addElement(obj);
}

@Override
public void add(int index, T obj)
{
addElement(obj);
}

@Override
public boolean addAll(Collection<? extends T> coll)
{
boolean added_all_elements = true;
for(T element:coll)
{
added_all_elements = addElement(element);
}

return added_all_elements;
}

@Override
public boolean addAll(int index, Collection<? extends T> coll)
{
boolean added_all_elements = true;
for(T element:coll)
{
added_all_elements = addElement(index, element);
}

return added_all_elements;
}

Step 4: Override set() methods in CustomArrayList

@Override
public T set(int index, T obj)
{
int num_of_occurrences = Collections.frequency(this, obj);
T pElement = super.get(index);

if(num_of_occurrences<2)
{
super.set(index, obj);
}

return pElement;
}

Step 5: Main program to perform Basic Testing of this Custom Collection

public class CustomArrayList {
public static void main(String[] args) {
MyCustomArrayList<String> cArrayList = new MyCustomArrayList<String>();
cArrayList.add("abc");
cArrayList.add("abc");
cArrayList.add("abc");

System.out.println(cArrayList);

//Custom Collection class is Compatible with existing Collection framework functionality
HashSet<String> hss = new HashSet<String>(cArrayList);
System.out.println(hss);
}
}

Advantages of developing Custom Collection Classes by following this approach is, the compatibility with the existing Collection framework functionality as shown in Step 5(main Driver program).

This works fine for elements of type String, what if I want to store elements of some other Type, say Employee. In such case equals() method need to be overridden to specify that when two different Employee objects can be equal, as shown below.

class Employee{private int emp_id;private String name;//add constructor to initialize data members
//add setter, getter methods
@Overridepublic String toString() {return "Employee [emp_id=" + emp_id + ", name=" + name + "]";}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Employee other = (Employee) obj;if (emp_id != other.emp_id)return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;return true;}}

Add below code snippet to main method, and observe in the output, that only two objects of Employee class exist in ArrayList.

MyCustomArrayList<Employee> cArrayListE = new MyCustomArrayList<Employee>();cArrayListE.add(new Employee(1, "name1"));cArrayListE.add(new Employee(1, "name1"));cArrayListE.add(new Employee(1, "name1"));System.out.println(cArrayListE);

Thanks for reading my Blog Post, and Lets explore few other possibilities of developing Custom Java Collections in my next Posts.

Click here to visit my Complete Core Java Course(25 hours of Video) with reading material and Source code examples

Read my other Post(s):

Spring, Spring Boot Annotations Cheat Sheet

--

--

Suresh Kumar

With about 23 Years of experience in Software development, currently into Corporate Training on Java Full Stack, Microservices, Angular, Design Patterns