Display numbers from 1 to 100 without loops or conditions [closed]

Know your libraries.

public class To100 {
    public static void main(String[] args) {
        String set = new java.util.BitSet() {{ set(1, 100+1); }}.toString();
        System.out.append(set, 1, set.length()-1);
    }
}

(You can use String.replaceAll to change the separator. For instance, .replaceAll(", ", " ") for space separation.)

Explanation:

  • java.util.BitSet is a handy little class that represents an arbitrarily large (non-sparse) set of positive integers. (It does have so bad bits: not final, unnecessarily thread-safe, doesn’t support building well, etc.)ta.
  • Extends BitSet allows me to write java.util only once. The JDK7 “diamond operator” should help reduce duplication with generic types, but no help for the more common situation. 🙁
  • The double braces are the Double Brace idiom – an anonymous inner class containing only an instance initialiser. It is a hack. It increase runtime size, and hence start-up time. Distribution size is negligible if you use pack200.gz. I think the modern world is ready for it. Your colleagues may not be. Perhaps start by using it for test da
  • BitSet.set sets a bit in the set (two completely different meanings of the word “set” there – I like it). It’s a half-open range – the top value exclusive; the bottom inclusive. Add 1 to the top to include 100.
  • BitSet.toString is actually precisely defined by the API docs.
  • append was added to PrintStream with the introduction of the Appendable interface in J2SE 5.0. It essentially does a substring and prints the result. (A little secret: this isn’t actually guaranteed by the spec to flush the output, but implementations always will.)
  • Starting the append at 1, and taking one off the length strips the braces from the string representation of BitSet.
  • “Know your libraries.” Taken from Josh Bloch. See Java Puzzlers, puzzle 94. It really is good to know what is in the libraries. At least know where to look. Save your time, save maintenance time and get it right first time.

Leave a Comment