Sobes.tech
Junior — Middle

How can you implement your own container in programming?

sobes.tech AI

Answer from AI

In Java, you can implement your own container by creating a class that stores a collection of objects and provides methods for adding, removing, and accessing elements. Typically, internal data structures such as arrays or lists are used for this.

Here's an example of a simple container that stores elements in an array and allows adding and retrieving elements:

public class SimpleContainer<T> {
    private Object[] elements;
    private int size = 0;

    public SimpleContainer(int capacity) {
        elements = new Object[capacity];
    }

    public void add(T element) {
        if (size == elements.length) {
            throw new RuntimeException("Container is full");
        }
        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;
    }
}

This container can be extended by adding methods for removal, search, iterators, and dynamic resizing of the internal array.

How can you implement your own container in… - sobes.tech