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.
Top comments (4)
Does it work for the
addAll()
method too?it will not work for
addAll()
, as here we have only the overridden theadd()
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.
If unique elements are matter, it is better to use implementation of Set rather than List.
Indeed.