From Int to Integer object, and makes a product to still have a lot of things

Java is one of the eight primitive int type, is one of the few things Java language is not an object, Integer int is the packaging, which uses a variable of type int to store data, a number of common operations between the integer, regular presentation so that programmers do not like to say, like the source programmers, we look at the source of it

 * @author  Lee Boynton
 * @author  Arthur van Hoff
 * @author  Josh Bloch
 * @author  Joseph D. Darcy
 * @since JDK1.0
 */
public final class Integer extends Number implements Comparable<Integer> {
    /**
     * A constant holding the minimum value an {@code int} can
     * have, -2<sup>31</sup>.
     */
    @Native public static final int   MIN_VALUE = 0x80000000;

    /**
     * A constant holding the maximum value an {@code int} can
     * have, 2<sup>31</sup>-1.
     */
    @Native public static final int   MAX_VALUE = 0x7fffffff;


    /**
     * The value of the {@code Integer}.
     *
     * @serial
     */
    private final int value;

    /**
     * Constructs a newly allocated {@code Integer} object that
     * represents the specified {@code int} value.
     *
     * @param   value   the value to be represented by the
     *                  {@code Integer} object.
     */
    public Integer(int value) {
        this.value = value;
    }

    /**
     * Constructs a newly allocated {@code Integer} object that
     * represents the {@code int} value indicated by the
     * {@code String} parameter. The string is converted to an
     * {@code int} value in exactly the manner used by the
     * {@code parseInt} method for radix 10.
     *
     * @param      s   the {@code String} to be converted to an
     *                 {@code Integer}.
     * @exception  NumberFormatException  if the {@code String} does not
     *               contain a parsable integer.
     * @see        java.lang.Integer#parseInt(java.lang.String, int)
     */
    public Integer(String s) throws NumberFormatException {
        this.value = parseInt(s, 10);
    }

Above this source is intercepted me out in the Integer class, these codes are not linked together, put them together, it is because I want to explain something, we carefully look at this code, Integer class is final, what does this show? value used to store variables also be modified private final, which in turn explains what? These are not looking at a little familiar with it? Yes, String objects, too, which shows Integer object is immutable, so in the future if asked Integer object is not immutable, remember the answer is oh. Why Integer objects are also designed to be immutable objects? In fact, I do not know, I did not find the answer from the document, but have seen for a description of the article in Yangxiaofeng teacher, the teacher said Yangxiaofeng Integer class is designed to have a relationship with immutable getInteger () method, the source getInteger () method as follows:

public static Integer getInteger(String nm, Integer val) {
    String v = null;
    try {
        v = System.getProperty(nm);
    } catch (IllegalArgumentException | NullPointerException e) {
    }
    if (v != null) {
        try {
            return Integer.decode(v);
        } catch (NumberFormatException e) {
        }
    }
    return val;
}

getInteger () method is used to get system properties, we have to set up a server port server through the property, if Integer variable, then we can easily change the value of this property, which makes our products exist Security Risk.

What I realized we simply chatted Integer class above, talk to int and Integer, naturally, ultimately, auto-boxing and auto-unboxing.

1, automatic packing, unpacking

Automatic boxing and unboxing is from the beginning of the introduction of JDK 1.5 features, it is a syntactic sugar, Java can automatically convert primitive types and packaging types depending on the context, simply means that the Java platform to ensure that the different writing produce the same bytecode after compiling, the run-time guarantees are equivalent. Automatic boxing and unboxing greatly simplifies the relevant programming.

Autoboxing : converting the original package types of process type

For example, to convert int type to integer type, which is the original type of change to the packaging type, at compile time, the compiler will automatically help us to do the conversion, the process of our programmers are not aware of, such as this Integer object assigned to the code:

Integer x = 3000;

This code after the compiler, will be converted into the following code:

Integer x = Integer.valueOf(3000);

This is the automatic packing process that you do not know, so it's called auto-boxing, boxing in the automatic process to valueOf () method to look at the source JDK in this method:

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

This method, the first conducted in front of a judge cache, if you do not know it, first ignored it, and finally return to the new Integer (i) object reference, this is to help you to call the constructor Integer class. This is the automatic packing.

Automatic unboxing : converting the package type into the original type of process

Int type Integer to convert type, which is converted to a package type into the original type of process, the process will involve automatically unpacking. Take a look at this code (which is a very messed up the code, actually nobody should write):

Integer mm = 1000;
int mmm = mm;

At compile time, the compiler code is compiled into the following code:

Integer mm = Integer.valueOf(1000);
int mmm = mm.intValue();

Mainly to see int mmm = mm.intValue();this line of code, with this line of code we write is not the same, to the use of a intValue () method to look at the source Integer class intValue () method:

/**
 * Returns the value of this {@code Integer} as an
 * {@code int}.
 */
public int intValue() {
    return value;
}

The role of this method is that the Integer object used to store the value of the return value variable, this is automatically unpacking, well, on automatic boxing and auto-unboxing we all know, remember autoboxing involved in the process cache it? Next we look together.

2, Integer caching policy

In autoboxing valueOf () method, we have seen a cache determination operation is to, Integer class has buffer pool, will use the cached values ​​frequently, in order to improve system performance, the autoloader in the process tank, first it determines whether the value is cached in the pool, if there is taken directly from the buffer pool referenced return, the object constructor function is invoked if not present. Cache is exclusive automatic packing operation, the constructor configured directly out Integer object even if the value in the buffer range, the buffer pool is not used. In the Integer class, a class to implement an internal cache, this internal class called IntegerCache, IntegerCache class source code is as follows:

    /**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */

    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() {}
    }

Java annotations from source and we can see that the default buffer range of -128 to 127 IntegerCache. But we can also set the maximum range of the cache by JVM command at startup, just add -XX at startup: AutoBoxCacheMax =
Parameters can be, but remember not to abuse this size can be set up, need to consider the full range, for example you set to 100,000, the number of which 100,000 will just start when you start to add memory, you think it will take how much memory? Doing more harm than good, Java company is set to -128 to 127 makes sense, most people find value in use are between -128 and 127, these values ​​occupy less memory than by function structure constructed on performance the object is much better. Value How do you use an Integer in the buffer range, to construct the object in the form Integer i = value if you value not in the cache range is used Integer i = form new Integer (value) construct Integer object to avoid automatic packing process. Finally, we look Integer object more commonly used method parseInt method

3, parseInt () method

Role parseInt () method is used to convert the integer string into an integer, parseInt and valueOf method requires a method to distinguish, there are a lot of people will ask what is the difference between these two methods, the last of the returns an int, all converted into a string of integral type integer, such as code

System.out.println(Integer.parseInt("+12"));
System.out.println(Integer.valueOf("+12"));

Finally, the output will be 12, because the result is the same as the output method calls valueOf use parseInt method to convert an integer integer type characters, and creates an Integer object 12 is in memory, and then return the object reference. The parseInt method will help you type characters into integer integer, not create additional objects. So they get the same results two is purely coincidental. Chou Chou together parseInt source:

public static int parseInt(String s, int radix)
                throws NumberFormatException
    {
        /*
         * WARNING: This method may be invoked early during VM initialization
         * before IntegerCache is initialized. Care must be taken to not use
         * the valueOf method.
         */

        if (s == null) {
            throw new NumberFormatException("null");
        }

        if (radix < Character.MIN_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " less than Character.MIN_RADIX");
        }

        if (radix > Character.MAX_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " greater than Character.MAX_RADIX");
        }

        int result = 0;
        boolean negative = false;
        int i = 0, len = s.length();
        int limit = -Integer.MAX_VALUE;
        int multmin;
        int digit;

        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar < '0') { // Possible leading "+" or "-"
                if (firstChar == '-') {
                    negative = true;
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != '+')
                    throw NumberFormatException.forInputString(s);

                if (len == 1) // Cannot have lone "+" or "-"
                    throw NumberFormatException.forInputString(s);
                i++;
            }
            multmin = limit / radix;
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                digit = Character.digit(s.charAt(i++),radix);
                if (digit < 0) {
                    throw NumberFormatException.forInputString(s);
                }
                if (result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                result *= radix;
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                result -= digit;
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
        return negative ? result : -result;
    }

When calling parseInt method, we can pass a variable radix, used to tell it what to convert binary, decimal is used by default.

The inadequacies of the article, hope a lot of pointing, learn together, and common progress

At last

Play a little advertising, welcomed the focus on micro-channel scan code number public: "flat head brother of technical Bowen" progress together.
Flathead brother of technical Bowen

Guess you like

Origin www.cnblogs.com/jamaler/p/11605945.html