Class Combinations

All Implemented Interfaces:

public class Combinations
extends java.lang.Object
implements java.util.Enumeration

The Combinations class provides an enumeration of all subsets of a group of n objects taken r at a time. The constructor for Combinations accepts the group as an array of Objects, along with the number to select.

For example, to choose 3 boys from a list of 5, begin with an array of names:

 Object[] boys = {“Alfred”, “Ben”, “Carl”, “Drew”, “Edwin”};
To see all combinations of these 5 names taken 3 at a time, create and use a Combinations enumeration:
  Combinations c = new Combinations(boys, 3);
 while (c.hasMoreElements()) {
  Object[] combo = (Object[])c.nextElement();
  for (int i = 0; i < combo.length; i++) {
   System.out.print((String)combo[i] + “ “);

This will print out a 10 line list:

 Alfred Ben Carl 
 Alfred Ben Drew 
 Alfred Ben Edwin 
 Alfred Carl Drew 
 Alfred Carl Edwin 
 Alfred Drew Edwin 
 Ben Carl Drew 
 Ben Carl Edwin 
 Ben Drew Edwin 
 Carl Drew Edwin 

Constructor Summary
Combinations(java.lang.Object[] inArray, int m)
          Create a Combination to enumerate through all subsets of the supplied Object array, selecting “m” at a time.
Method Summary
 boolean hasMoreElements()
 java.lang.Object nextElement()
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail


public Combinations(java.lang.Object[] inArray,
                    int m)
             throws CombinatoricException
Create a Combination to enumerate through all subsets of the supplied Object array, selecting “m” at a time.

m - int the number to select in each choice
CombinatoricException - if m is greater than the length of inArray, or less than 0.
Method Detail


public boolean hasMoreElements()
Specified by:
hasMoreElements in interface java.util.Enumeration
true, unless we have already returned the last combination.


public java.lang.Object nextElement()
Specified by:
nextElement in interface java.util.Enumeration
java.lang.Object, the next combination from the supplied Object array.

Actually, an array of Objects is returned. The declaration must say just “Object,” because the Combinations class implements Enumeration, which declares that the “nextElement()” returns a plain Object. Users must cast the returned object to (Object[]).