Varargs for 1 to N

Varargs allow you to pass a variable number of arguments to a method. The varargs param always appears last in the list of arguments. A varargs param can be passed by the caller either as an array, or as a sequence of 0..N items. When a sequence of items is passed, Java will automatically convert those items into an array.

Sometimes you need to change 0..N to 1..N, or perhaps to some other case (2..N, and so on), where the minimum number of items isn't 0, but some integer greater than 0.

In that case, there's a simple trick to enforce such a policy. You first pass a regular, non-vararg param of the same type.

void doSomething(Thing thing, Thing... things);

Example

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/** 
 An electric circuit.
 @since Java 5 
*/
final class Circuit {
  
  /**
   * Constructor. 
   * Policy: the circuit needs at least 1 element!! 
   * That is, the circuit has 1..N elements, not 0..N.
   * 
   * Varargs can only be used in the final position, with the
   * last argument in the sequence of arguments.
   * 
   * Overloading methods that use varargs is tricky, and should
   * usually be avoided.
   */
  Circuit(CircuitElement element, CircuitElement... elements){
    this.elements.add(Objects.requireNonNull(element));
    this.elements.addAll(Arrays.asList(elements));
  }
  
  /** The kind of circuit element. */
  enum ElementType {
    RESISTOR, CAPACITOR, INDUCTOR, BATTERY;
  }
  
  /** An element of an electric circuit. Immutable. */
  static final class CircuitElement {
    CircuitElement(ElementType elementType, Double spec){
      this.elementType = Objects.requireNonNull(elementType);
      this.spec = Objects.requireNonNull(spec);
    }
    ElementType getElementType(){ return elementType; }
    /** 
     Resistance, capacitance, inductance, voltage.
     Units defined by some convention. 
    */
    Double getSpec(){ return spec; }
    private ElementType elementType;
    private Double spec;
  }
  
  //..elided

  /** A simplistic model; should really be a network, of course. */
  private List<CircuitElement> elements = Collections.emptyList();
  
  /** Informal test. */
  public static void main(String... args) {
    CircuitElement a = new CircuitElement(ElementType.BATTERY, 10.0); //volts
    CircuitElement b = new CircuitElement(ElementType.RESISTOR, 200.0); //ohms
    CircuitElement c = new CircuitElement(ElementType.CAPACITOR, 300.0E-12); //farads
    
    //Circuit zero = new Circuit(); //doesn't compile!
    Circuit one = new Circuit(a);
    Circuit two = new Circuit(a, b);
    Circuit three = new Circuit(a, b, c);
 
    //varargs can be passed as an array, if you wish
    CircuitElement[] others = {b, c};
    Circuit threePrime = new Circuit(a, others);
  }
}