1

I am looking at an IntegerCache class, but it has a usage I can't understand. There is a private constructor on the last line, but I don't understand the purpose. What does it do?

private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];

    static {
        // high value may be configured by property
        int h = 127;
        String integerCacheHighPropValue =
        sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            try {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
            } catch( NumberFormatException nfe) {
                // If the property cannot be parsed into an int, ignore it.
            }
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);

        // range [-128, 127] must be interned (JLS7 5.1.7)
        assert IntegerCache.high >= 127;
    }

    private IntegerCache() {}
 }
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
S.Xin
  • 11
  • 2

2 Answers2

3

That is an empty constructor that is also private, preventing instantiation of the the class. The class is intended to be used only for its static properties and no instance of the class can be created.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
3

By default, the Java compiler will insert an empty public constructor if no constructor is provided. By explicitly adding an empty private constructor

private IntegerCache() {}

the compiler will not add a default constructor. See also JLS-8.8.9. Default Constructor and JLS-8.8.10. Preventing Instantiation of a Class which says (in part)

A class can be designed to prevent code outside the class declaration from creating instances of the class by declaring at least one constructor, to prevent the creation of a default constructor, and by declaring all constructors to be private.

A public class can likewise prevent the creation of instances outside its package by declaring at least one constructor, to prevent creation of a default constructor with public access, and by declaring no constructor that is public.

Community
  • 1
  • 1
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249