//: c09:Statistics.java // From 'Thinking in Java, 2nd ed.' by Bruce Eckel // www.BruceEckel.com. See copyright notice in CopyRight.txt. // Simple demonstration of HashMap. // // import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.util.*; import com.bruceeckel.swing.*; import com.bruceeckel.util.*; public class Statistics extends JApplet { JTextArea Xout = new JTextArea(20, 50); public void init() { Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(new JLabel("Statistics!")); cp.add(new JScrollPane(Xout)); HashMap hm = new HashMap(); for(int i = 0; i < 260; i++) { Character r = new Character((char)(Math.random() * 26 + 'a')); if(hm.containsKey(r)) ((Counter)hm.get(r)).i++; else hm.put(r, new Counter()); } for(int i = 0; i < 26; i++) { Character r = new Character((char)(i+'a')); if(hm.containsKey(r)){ Counter c = (Counter)hm.get(r); Xout.append (r + " -> " + c + "\n"); } } } class Counter { int i = 1; public String toString() { return Integer.toString(i); } } public static void main(String[] args) { Console.run(new Statistics(), 600, 400); } } ///:~