public class Collections2
1: //: com:bruceeckel:util:Collections2.java
2: // From 'Thinking in Java, 2nd ed.' by Bruce Eckel
3: // www.BruceEckel.com. See copyright notice in CopyRight.txt.
4: // To fill any type of container
5: // using a generator object.
6: package com.bruceeckel.util;
7: import java.util.*;
9: public class Collections2 {
10: // Fill an array using a generator:
11: public static void
12: fill(Collection c, Generator gen, int count) {
13: for(int i = 0; i < count; i++)
14: c.add(gen.next());
15: }
16: public static void
17: fill(Map m, MapGenerator gen, int count) {
18: for(int i = 0; i < count; i++) {
19: Pair p = gen.next();
20: m.put(p.key, p.value);
21: }
22: }
23: public static class RandStringPairGenerator
24: implements MapGenerator {
25: private Arrays2.RandStringGenerator gen;
26: public RandStringPairGenerator(int len) {
27: gen = new Arrays2.RandStringGenerator(len);
28: }
29: public Pair next() {
30: return new Pair(gen.next(), gen.next());
31: }
32: }
33: // Default object so you don't have
34: // to create your own:
35: public static RandStringPairGenerator rsp =
36: new RandStringPairGenerator(10);
37: public static class StringPairGenerator
38: implements MapGenerator {
39: private int index = -1;
40: private String[][] d;
41: public StringPairGenerator(String[][] data) {
42: d = data;
43: }
44: public Pair next() {
45: // Force the index to wrap:
46: index = (index + 1) % d.length;
47: return new Pair(d[index][0], d[index][1]);
48: }
49: public StringPairGenerator reset() {
50: index = -1;
51: return this;
52: }
53: }
54: // Use a predefined dataset:
55: public static StringPairGenerator geography =
56: new StringPairGenerator(
57: CountryCapitals.pairs);
58: // Produce a sequence from a 2D array:
59: public static class StringGenerator
60: implements Generator {
61: private String[][] d;
62: private int position;
63: private int index = -1;
64: public
65: StringGenerator(String[][] data, int pos) {
66: d = data;
67: position = pos;
68: }
69: public Object next() {
70: // Force the index to wrap:
71: index = (index + 1) % d.length;
72: return d[index][position];
73: }
74: public StringGenerator reset() {
75: index = -1;
76: return this;
77: }
78: }
79: // Use a predefined dataset:
80: public static StringGenerator countries =
81: new StringGenerator(CountryCapitals.pairs,0);
82: public static StringGenerator capitals =
83: new StringGenerator(CountryCapitals.pairs,1);
84: } ///:~