DEV Community

Code Green for CodeGreen

Posted on • Updated on

In Java how to create a custom ArrayList that doesn't allow duplicate? #Interview Question

Creating a Custom ArrayList in Java that Doesn't Allow Duplicates

=================================================================

In Java, you can create a custom ArrayList that ensures no duplicate elements are added by extending the ArrayList class and overriding the add method.

import java.util.ArrayList;

public class CustomArrayList<E> extends ArrayList<E> {

    // Override add method to prevent duplicates
    @Override
    public boolean add(E e) {
        if (!contains(e)) {
            return super.add(e);
        }
        return false;
    }

    public static void main(String[] args) {
        CustomArrayList<Integer> list = new CustomArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(2); // This duplicate will not be added

        System.out.println(list); // Output: [1, 2, 3]
    }
}
Enter fullscreen mode Exit fullscreen mode

This custom ArrayList implementation checks if an element already exists before adding it. If the element is not found, it adds the element using the superclass's add method. Otherwise, it returns false, indicating that the element was not added due to duplication.

Top comments (4)

Collapse
 
blackr1234 profile image
blackr1234

Does it work for the addAll() method too?

Collapse
 
codegreen profile image
Code Green

it will not work for addAll(), as here we have only the overridden the add() method.
And this is just for demonstration purpose, not to be used in real world as @saladlam rightly said Set would be better for unique list.
These type of questions are only asked in Interview, where they want to check if have correct understanding of Collections and are you capable enough to change the default behavior.

Collapse
 
saladlam profile image
Salad Lam

If unique elements are matter, it is better to use implementation of Set rather than List.

Collapse
 
blackr1234 profile image
blackr1234

Indeed.