Treating first/last loop iterations differently
Imagine you have a list of Kittens, and you want to print out a summary of them, saying "My kittens are called Bob, James, John, and Ally." You need to treat the first and last element of the list differently from the rest, lest you end up with superfluous commas in the text. You also need to deal with the cases of there being only one kitten, or no kittens at all.
To do this, you can avail yourself of a Counter class that keeps track of where you are in the iteration:
1 2 String kittenDesc = "I have no kittens."; 3 Counter kc = new Counter(kittens); 4 for (Kitten k : kittens) switch(kc.next()) { 5 case one: kittenDesc = "My kitten is called " + k.getName() + "."; break; 6 case first: kittenDesc = "My kittens are called " + k.getName(); break; 7 case item: kittenDesc += ", " + k.getName(); break; 8 case last: kittenDesc += " and " + k.getName() + "."; break; 9 } 10 11 package com.zarkonnen.util; 12 13 import java.util.Collection; 14 15 /** 16 * Used for keeping track of where you are in a collection/array being iterated over. Use by 17 * initialising with the collection/array before the loop and embedding a switch on the next() Mode 18 * value into the loop. 19 * 20 * LICENCE: This code is licenced under a BSD licence. Feel free to alter and redistribute. 21 * 22 * @author David Stark, http://www.zarkonnen.com 23 * @version 1.0 (2007-07-11) 24 */ 25 public class Counter { 26 /** 27 * An enumeration of modes identifying where in the collection/array we are. 28 */ 29 public enum Where { 30 /** The only element of an array/collection of size 1. */ one, 31 /** The first element. */ first, 32 /** The last element of the array/collection. */ last, 33 /** Any other element somewhere in the middle. */ item 34 } 35 36 private int size; 37 private int nextIndex = 0; 38 39 /** 40 * @param c A collection to keep track of. If its size changes between now and the 41 * iteration, strange things will happen. 42 */ 43 public Counter(Collection c) { 44 size = c.size(); 45 } 46 47 /** 48 * @param a An array to keep track of. If its size changes between now and the iteration, 49 * strange things will happen. 50 */ 51 public Counter(Object[] a) { 52 size = a.length; 53 } 54 55 /** 56 * @return A Where enum value for where in the array/collection we now are: 57 * <ul> 58 * <li><strong>one</strong> at the only element of an array/collection of size 1</li> 59 * <li><strong>first</strong> at the first element</li> 60 * <li><strong>last</strong> at the last element</li> 61 * <li><strong>item</strong> at any other element</li> 62 * </ul> 63 */ 64 public Where next() { 65 return size == 1 ? Where.one : 66 nextIndex++ == 0 ? Where.first : 67 nextIndex == size ? Where.last : 68 Where.item ; 69 } 70 71 /** 72 * @return Which index of the array/collection we're currently at. 73 */ 74 public int index() { 75 return nextIndex == 0 ? 0 : nextIndex - 1; 76 } 77 }