In Java, a custom List can be implemented by creating a class that implements the List interface and providing implementations for its methods. This can be useful when the standard implementations of List provided by Java do not meet the specific needs of the application.
Here is an example implementation of a custom List that stores its elements in an array and provides basic methods for adding and removing elements:
public class CustomList<E> implements List<E> {
private E[] elements;
private int size;
@SuppressWarnings("unchecked")
public CustomList(int initialCapacity) {
elements = (E[]) new Object[initialCapacity];
size = 0;
}
// Implementation of List methods
@Override
public boolean add(E e) {
if (size == elements.length) {
resize();
}
elements[size++] = e;
return true;
}
@Override
public E get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
return elements[index];
}
@Override
public int size() {
return size;
}
// Other List methods not shown
private void resize() {
int newCapacity = elements.length * 2;
elements = Arrays.copyOf(elements, newCapacity);
}
}
This implementation uses an array to store the elements of the list, and doubles the size of the array when it becomes full to avoid costly resizing operations.
One use case for implementing a custom List might be to optimize performance for specific use cases, such as when the list is frequently accessed or modified in a particular way that is not well-served by the standard implementations provided by Java. Additionally, custom List implementations can be useful for integrating with other parts of an application that have specific requirements for the behavior of the List.