Class CollectionSampler<T>

java.lang.Object
org.apache.commons.rng.sampling.CollectionSampler<T>
Type Parameters:
T - Type of items in the collection.
All Implemented Interfaces:
ObjectSampler<T>, SharedStateObjectSampler<T>, SharedStateSampler<SharedStateObjectSampler<T>>

public class CollectionSampler<T> extends Object implements SharedStateObjectSampler<T>
Sampling from a Collection.

Sampling uses UniformRandomProvider.nextInt(int).

Since:
1.0
  • Field Details

  • Constructor Details

    • CollectionSampler

      public CollectionSampler(UniformRandomProvider rng, Collection<T> collection)
      Creates a sampler.
      Parameters:
      rng - Generator of uniformly distributed random numbers.
      collection - Collection to be sampled. A (shallow) copy will be stored in the created instance.
      Throws:
      IllegalArgumentException - if collection is empty.
    • CollectionSampler

      private CollectionSampler(UniformRandomProvider rng, List<T> collection)
      Parameters:
      rng - Generator of uniformly distributed random numbers.
      collection - Collection to be sampled.
  • Method Details

    • sample

      public T sample()
      Picks one of the items from the collection passed to the constructor.
      Specified by:
      sample in interface ObjectSampler<T>
      Returns:
      a random sample.
    • withUniformRandomProvider

      public CollectionSampler<T> withUniformRandomProvider(UniformRandomProvider rng)
      Create a new instance of the sampler with the same underlying state using the given uniform random provider as the source of randomness.
      Specified by:
      withUniformRandomProvider in interface SharedStateSampler<T>
      Parameters:
      rng - Generator of uniformly distributed random numbers.
      Returns:
      the sampler
      Since:
      1.3
    • toList

      private static <T> List<T> toList(Collection<T> collection)
      Convert the collection to a list (shallow) copy.

      This method exists to raise an exception before invocation of the private constructor; this mitigates Finalizer attacks (see SpotBugs CT_CONSTRUCTOR_THROW).

      Type Parameters:
      T - Type of items in the collection.
      Parameters:
      collection - Collection.
      Returns:
      the list copy
      Throws:
      IllegalArgumentException - if collection is empty.