Use generic collection interfaces as parameters

Sunday, 10 April 2005

Functions that take collection parameters should take the generic parameter. E.g. don’t do this:

public void process(ArrayList list);

do this instead:

public void process(List list);

This avoids putting unnecessary requirements on the parameter. In particular, you can do these:

thing.processList(Collections.EMPTY_LIST);
thing.processList(Collections.singletonList(item));
LinkedList linkedList = getLinkedList();
thing.processList(linkedList);

instead of having to do these:

thing.processList(new ArrayList());
ArrayList list = new ArrayList(1);
list.add(item);
thing.processList(list);
LinkedList linkedList = getLinkedList();
thing.processList(new ArrayList(linkedList));

Tags:

Share this page:
  • Twitter
  • Digg
  • Slashdot
  • del.icio.us
  • Google Bookmarks
  • DZone
  • LinkedIn
  • Reddit
  • Facebook
  • Print

One comment

You can leave a comment, or trackback from your own site.

  1. Of course. This don’t just apply to collections but potentially to any class. This is the rule #1 of OO Design Patterns.

Leave a comment