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:

2 comments

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.

  2. I have noticed you don’t monetize your website, don’t waste your traffic, you can earn extra bucks every month because you’ve
    got hi quality content. If you want to know how to make extra bucks, search for:
    Mrdalekjd methods for $$$

Leave a comment