In Java how to create a custom ArrayList that doesn’t allow duplicate?

RMAG news

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]
}
}

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.

Please follow and like us:
Pin Share