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

Java Collections · Guru · question 100 of 100

How do you implement a custom List in Java that supports efficient random access and range queries, and what are some use cases for doing so?

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

To implement a custom list in Java that supports efficient random access and range queries, we can use an array-based approach, where the elements are stored in an array and accessed by their indices. This approach allows for constant time random access and efficient range queries, as we can simply iterate over the relevant portion of the array.

Here’s an example implementation of a custom list in Java that supports random access and range queries:

public class CustomList<T> {
    private Object[] elements;
    private int size;

    public CustomList(int initialCapacity) {
        this.elements = new Object[initialCapacity];
        this.size = 0;
    }

    public void add(T element) {
        if (size == elements.length) {
            resize();
        }
        elements[size++] = element;
    }

    @SuppressWarnings("unchecked")
    public T get(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException();
        }
        return (T) elements[index];
    }

    public int size() {
        return size;
    }

    public CustomList<T> subList(int fromIndex, int toIndex) {
        if (fromIndex < 0 || toIndex > size || fromIndex > toIndex) {
            throw new IndexOutOfBoundsException();
        }
        CustomList<T> sublist = new CustomList<>(toIndex - fromIndex);
        for (int i = fromIndex; i < toIndex; i++) {
            sublist.add(get(i));
        }
        return sublist;
    }

    private void resize() {
        int newCapacity = elements.length * 2;
        elements = Arrays.copyOf(elements, newCapacity);
    }
}

In this implementation, we use an array to store the elements and resize the array when it becomes full. We also provide methods for getting the element at a specific index and creating a sublist of the original list from a range of indices.

Some use cases for a custom list like this include implementing a data structure that requires efficient random access and range queries, such as a cache or a sliding window buffer for data processing.

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