0

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.

7
  • You can certainly override methods and implement those interfaces, but I'm not quite sure what you mean by using both? Arraylist and Linkedlist are fundamentally different data structures - the former is a contiguous block of memory, and the latter is disjointed. Can you elaborate on what you mean by " deals with both cases" ? Commented Dec 20, 2016 at 3:35
  • both cases... as in ? Commented Dec 20, 2016 at 3:35
  • @GurwinderSingh what do u mean can u elaborate further? Commented Dec 20, 2016 at 3:35
  • It means your question as it stands is not clear enough to answer - add more detail, perhaps an example, read stackoverflow.com/help/how-to-ask if you haven't yet. Commented Dec 20, 2016 at 3:41
  • @pvg updated with some examples Commented Dec 20, 2016 at 3:46

1 Answer 1

1

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
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks but is there vanilla Java way to do this?
Only creating your own of List that delegates all methods (including equals/hashCode) to an underlying List.
Thanks. I've upvoted you :) Is there a good example where I can find vanilla Java implementation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.