Java List Tip


As I mentioned before, every Java programmer must own Effective Java by Joshua Bloch. Here is one of the tips from the book. It discusses is "Minimizing the scope of local variables" (Item 29). Part of this tip, that might be of interest to developers here is: Iteration of List's In his book, Bloch discusses the use of For loops over While loops when iterating through the contents of a list. This will minimize the scope of variables assuming that the variables are not needed later in the method. For Example,
for (Iterator i = c.iterator(); i.hasNext(); )
{
doSomething(i.next() );
}

To see why this for loop preferable to the more obvious while loop, consider the following code fragment, which contains two while loops and one bug:

Iterator i = c.iterator(); while (i.hasNext() )
{
doSomething(i.next());
}
Iterator i2 = c2.iterator();
while (i.hasNext() )
{
//BUG! doSomethingElse(i2.next());
}

The second loop contains a cut and paste error: It initiates a new loop variable, i2, but uses the old one, i. This will compile with out error and also run with error. The second loop will always terminate immediately and look like c2 does not contain anything. If the same cut and paste were done with the for loop, the loop variable from the first loop would not be in scope in the second loop and it would cause a compile error:

for (Iterator i = c.iterator(); i.hasNext(); )
{
doSomething(i.next() );
……
}
//Compile-time error- the symbol i cannot be resolved
for (Iterator i2 = c2.iterator(); i.hasNext(); )
{
doSomething(i2.next() );
……
}

Here is another tip for faster access to the loop when using random access List implementations such as ArrayList and Vector: for (int i =0, n = list.size(); i )The use of the second variable is essential to the performance of the idion. Without it, the loop would have to call the size method oncer per iteration. This is very useful if you know that there may be a large amount of elements in the list and will save vital time when iterating through the list. One note that Bloch make on this is: "Using this idiom is acceptable when you are sure the list really does provide random access: otherwise it displays quadratic performance". Hope this helps when working with Lists or Arraylists. Stephen For more details on this tip see Effective Java by Joshua Bloch

  1. No comments yet.
(will not be published)