How to create extensible dynamic array in Java without using pre-made classes?

AndrejaKo picture AndrejaKo · May 26, 2010 · Viewed 17.4k times · Source

Yeah, it's a homework question, so givemetehkodezplsthx! :)

Anyway, here's what I need to do:
I need to have a class which will have among its attributes array of objects of another class. The proper way to do this in my opinion would be to use something like LinkedList, Vector or similar. Unfortunately, last time I did that, I got fire and brimstone from my professor, because according to his belief I was using advanced stuff without understanding basics.

Now next obvious solution would be to create array with fixed number of elements and add checks to get and set which will see if the array is full. If it is full, they'd create new bigger array, copy older array's data to the new array and return the new array to the caller. If it's mostly empty, they'd create new smaller array and move data from old array to new. To me this looks a bit stupid. For my homework, there probably won't be more that 3 elements in an array, but I'd like to make a scalable solution without manually calculating statistics about how often is array filled, what is the average number of new elements added, then using results of calculation to calculate number of elements in new array and so on.

By the way, there is no need to remove elements from the middle of the array.

Any tips?

Answer

Andrei Fierbinteanu picture Andrei Fierbinteanu · May 26, 2010
class test {
    private Object[] objects;
    private int size;

    public test() {
        objects = new Object[10];
        size = 0;
    }

    public void push(Object o) {
        if (objects.length == size) {
            throw new RuntimeException("This wouldn't happen if I didn't have to reinvent the wheel");
        }
        objects[size] = o;
        size++;
    }

    public Object pop() {
        size--;
        Object o = objects[size];
        objects[size] = null;
        return o;
    }
}

Just kidding. I think you're best bet is to implement your own linked list and then use that in your class. Something like:

class Element {
    Object val;
    Element next;
    Element prev;

    public Element(Object val, Element next, Element prev) {
        this.val = val;
        this.next = next;
        this.prev = prev;
    }

}

class LinkedList {
    Element head;
    Element tail;

    public void add(Object o) {
        Element el = new Element(o, null, tail);
        tail.next = el;
    }

    public Object remove() {
        Element o = tail;
        tail = o.prev;
        tail.next = null;
        return o.val;
    }
}