/** * This code is from the book: * Winder, R and Roberts, G (1998) * Developing Java Software * John Wiley & Sons. * It is copyright (c) 1997 Russel Winder * and Graham Roberts. */ import java.util.Vector; class l1Nest2{//Class3 private Vector items = new Vector(); static private class CountedString{ public CountedString(String s){ item = s; } String item; int count = 1; } //If the String argument already exists, //increment the count. Otherwise add a //new CountedString with a count of 1 public void addString(String s){ CountedString tmp = searchFor(s); if (tmp == null){ items.addElement(new CountedString(s)); } else{ tmp.count++; } } //Return the number of times a string has been added public int getCount(String s){ CountedString tmp = searchFor(s); return tmp == null ? 0 : tmp.count; } //If a string has already been added, //return its CountedString //object, otherwise return null. private CountedString searchFor(String s){ for (int i = 0; i < items.size(); i++){ CountedString tmp = (CountedString)items.elementAt(i); if ((tmp.item).equals(s)) return tmp; } return null; } public static void main(String[] args){ l1Nest2 c3 = new l1Nest2(); c3.addString("hello"); c3.addString("world"); c3.addString("world"); c3.addString("hello"); c3.addString("hello"); c3.addString("world"); c3.addString("hello"); c3.addString("world"); c3.addString("hello"); c3.addString("hello"); c3.addString("world"); c3.addString("world"); System.out.println("hello as been added " + c3.getCount("hello") + " times"); System.out.println("world as been added " + c3.getCount("world") + " times"); System.out.println("Hello as been added " + c3.getCount("Hello") + " times"); } } /******** sample compilation & run ******* # javac l1Nest2.java # java l1Nest2 hello as been added 6 times world as been added 6 times Hello as been added 0 times # ******************************************/