SWE/CS 332 In Class Exercise # 20

Name(s):
// Chooser - a class badly in need of generics!
// Bloch 3rd edition, Chapter 5, Item 28:  Prefer lists to arrays

public class Chooser {
   private final Object[] choiceArray;

   public Chooser (Collection choices) {
      choiceArray = choices.toArray();
   }

   public Object choose() { 
      Random rnd = ThreadLocalRandom.current();
      return choiceArray [rnd.nextInt(choiceArray.length)];
   }
}
Generify by adding a type to the Chooser class and adopting Bloch's advice about arrays and lists. Make whatever corresponding changes are necessary.

Write a (partial) contract for the choose() method. What's ugly about this?

Can you come up with a client-visible invariant that allows you to get rid of the precondition?

How should you capture that client-invariant with the rep-invariant?

Rewrite the contract for choose() and supply a contract for the constructor.