import java.util.*; class Looper { static int countHellos( List words ) { int hellosSoFar = 0; while (!words.isEmpty()) { // LOOP INVARIANT : the number of times "hello" occurs // in `words` plus hellosSoFar is the same, each time through loop. hellosSoFar += ((words.get(0)).equals("hello") ? 1 : 0); words = words.subList(1,words.size()); } return hellosSoFar; } static void testCountHellos() { List vocab = new LinkedList(); vocab.add( 0, "hello" ); vocab.add( 0, "The apple" ); // Like a mutating version of cons?? vocab.add( 0, "hello" ); vocab.add( 0, "aloha" ); System.out.println( "Expect 0, got " + countHellos(new ArrayList()) ); System.out.println( "Expect 2, got " + countHellos(vocab) ); } }