View Javadoc

1   /*
2    * Copyright 2011 Király Attila
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package com.github.cage;
17  
18  import java.util.Random;
19  
20  /**
21   * An {@link IGenerator} implementation that returns a randomly chosen element
22   * from a predefined set of objects when {@link #next()} is called. This class
23   * is thread safe.
24   * 
25   * @param <T>
26   *            the type of objects generated by this class
27   * 
28   * @author akiraly
29   */
30  public class ObjectRoulette<T> implements IGenerator<T> {
31  	private final T[] candidates;
32  
33  	private final Random rnd;
34  
35  	/**
36  	 * Constructor.
37  	 * 
38  	 * @param rnd
39  	 *            random generator to be used, can be null
40  	 * @param candidates
41  	 *            the set of objects to choose from; not null, not empty
42  	 */
43  	public ObjectRoulette(Random rnd, T... candidates) {
44  		if (candidates == null || candidates.length < 1) {
45  			throw new IllegalArgumentException("No candidates given.");
46  		}
47  		this.candidates = candidates;
48  		this.rnd = rnd != null ? rnd : new Random();
49  	}
50  
51  	public T next() {
52  		return candidates[rnd.nextInt(candidates.length)];
53  	}
54  
55  	/**
56  	 * @return the set of objects to choose from
57  	 */
58  	public T[] getCandidates() {
59  		return candidates;
60  	}
61  }