/**
* This code is from the book:
* Winder, R and Roberts, G (1998)
* Developing Java Software</em>
* John Wiley & Sons.
* It is copyright (c) 1997 Russel Winder
* and Graham Roberts.
*/
import java.util.Vector;
class StringCounter
{
private static 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;
}
// Private helper method.
// 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)
{
Class3 c3 = new Class3();
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");
}
private Vector items = new Vector();
}