Passionate Engineer
Passionate Engineer

Reputation: 10412

Implement custom add method to Java

I have a code that has ArrayList and LinkedList and would like to implement a custom add method class that I can use for both cases.

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(anotherList);

LinkedList<Integer> listTwo = new LinkedList<Integer>();
listTwo.add(newList);

I would like to log for every add method for both LinkedList and ArrayList.

I would have thought implementing Java list interface would be sufficient. Is there a recommended approach of doing this?

I understand there are multiple ways of solving this thing.

Upvotes: 0

Views: 1298

Answers (1)

Kiskae
Kiskae

Reputation: 25573

If you can afford to include Guava as a dependency then it has a ready-made solution for delegating the default collections: https://github.com/google/guava/wiki/CollectionHelpersExplained#forwarding-decorators

The example listed matches your example use-case:

class AddLoggingList<E> extends ForwardingList<E> {
  final List<E> delegate; // backing list
  @Override protected List<E> delegate() {
    return delegate;
  }
  @Override public void add(int index, E elem) {
    log(index, elem);
    super.add(index, elem);
  }
  @Override public boolean add(E elem) {
    return standardAdd(elem); // implements in terms of add(int, E)
  }
  @Override public boolean addAll(Collection<? extends E> c) {
    return standardAddAll(c); // implements in terms of add
  }
}

Upvotes: 1

Related Questions