Luca Fülbier Luca Fülbier - 24 days ago 10
Java Question

Collection implementation that mostly delegates to a class member

I want to implement a

Collection
that represents a sorted collection of items. The main reason i need a special
Collection
instead of just calling
sort()
on a list is that i need specific behavior for the
add()
method to improve performance. The rest of the
Collection
will mostly just delegate to a class member, probably an
ArrayList
.

Is there a way to delegate part of the
Collection
interface to my class member instead of having to write all the delegation by hand like this?

public void clear() {
myList.clear();
}

public int hashCode() {
return myList.hashCode()
}

...

Answer

As mentioned by Eran you can extend an ArrayList and the methods which adds elements to the underlying collection.

An example:

import java.util.ArrayList;
import java.util.Collection;

public class MyCustomCollection<E> extends ArrayList<E> {

    private void myCustomBehaviour() {
        // TODO: Implement.
    }

    @Override
    public boolean add(E e) {
        myCustomBehaviour();
        return super.add(e);
    }

    @Override
    public void add(int index, E element) {
        myCustomBehaviour();
        super.add(index, element);
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {
        myCustomBehaviour();
        return super.addAll(c);
    }

    @Override
    public boolean addAll(int index, Collection<? extends E> c) {
        myCustomBehaviour();
        return super.addAll(index, c);
    }
}

The ArrayList is an implementation of the Collection interface of which there are several. Some of which are HashSet, HashMap, LinkedList and more.