8 December 2009

Unexpected behaviour of ArrayLists size method

Today I just learned something more about Javas ArrayList and my Debugger after an half an hour of trying to find out what is wrong with my code.
I had the strange situtation that the debugger told me that my list contained 6 elements but the size method of that list returned a value of 7 (see figure below). Apparently the ArrayList accepts null values without complaining about it and these null values are going to modify the size of the list but the debugger - in the case the debugger of IntelliJ IDEA 9 RC1 - filters null values and does not display them.




With the following listing you can reproduce this behaviour using IntelliJ IDEA (or your prefered IDE).

import java.util.ArrayList;
import java.util.List;

public class FunnyLists
{
   public static void main(String[] args)
   {
      List<String>
 list = new ArrayList<String>();
      list.add("Hello");
      list.add(null);
      list.add("World");        

      System.out.println("Size: " + list.size());

      for(String element : list) {
         System.out.println("Element: " + element);
      }
   }
}



This listing generates the following output:
Size: 3


Element: Hello
Element: null
Element: World

No comments: