Gunjan Doshi

Startups, Entrepreneurship, Agility, Management & Leadership, Metrics

Overusing ArrayLists

April 6th, 2005 by gunjandoshi

ArrayList is one of the most preffered collection types used by the programmers. Whenever, in need of a collection, the first thing a programmer tries to use is an ArrayList.

Consider the following code snippet; first the unit-test:

  FruitBasket fruitBasket = new FruitBasket();
  fruitBasket.add(FruitType.Oranges);
  fruitBasket.add(FruitType.Oranges);
  assertEquals("Should have only one set of oranges", 1, fruitBasket.countOf (FruitType.Oranges));

Now the implementation :

  public void add(FruitType fruitType){
    List fruitBasket = new ArrayList();
...
    //Before adding oranges, make sure they do not exist
    if(!fruitBasket.contains(fruitType))
       fruitBasket.add(fruitType);
  }

This is nothing wrong with this. However, the if statement is only required because we used an ArrayList.

We refactor the above code to use a HashSet. HashSet is an unordered set that contains only unique values.

The code is simplified to:

  public void add(FruitType fruitType){
    Set fruitBasket = new HashSet();

    fruitBasket.add(fruitType);
  }

In addition, we found few other tests that checked if the fruitBasket.remove(FruitType.Oranges) removed all the oranges. This is because the remove(object) method of an ArrayList only removes the first object it finds. After implementing it as Set, we had an added advantage of not having to worry about these side-effects.

The project I am helping, has lots of code like this; except that they are not fruits. Upon retrospect, we discovered that the ArrayList was over-used because it is always very natural for most of the programmers to resort to an ArrayList, whenever a collection is needed.

Take-home point: Before using an ArrayList, find if there is a better alternative.

Tags: No Comments

Leave a Comment

0 responses so far ↓

There are no comments yet...Kick things off by filling out the form below.