WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java Collections · Advanced · question 51 of 100

How do you implement a custom List in Java, and what are some use cases for doing so?

📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

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.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Collections interview — then scores it.
📞 Practice Java Collections — free 15 min
📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

All 100 Java Collections questions · All topics