Analyse du code source 2.Integer

1. Code source de la plage de valeurs et du type de données de base

public final class Integer extends Number implements Comparable<Integer> {
    
    
 	//该值用于定义Integer取值的最小值
    @Native public static final int   MIN_VALUE = 0x80000000;
    
    //该值用于定义Integer取值的最大值
    @Native public static final int   MAX_VALUE = 0x7fffffff;

    //该值用于定义Integer的基本数据类型
    @SuppressWarnings("unchecked")
    public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
}

Analyse du code source

  1. Integer est un type modifié par final, qui hérite de la classe Number et implémente l'interface Comparable.
  2. La valeur minimale de Integer est -2 ^ 31 et la valeur maximale est 2 ^ 31-1.
  3. Le type de données de base de Integer est int.

2. code source toString

public final class Integer extends Number implements Comparable<Integer> {
    
    
	public static String toString(int i) {
    
    
        if (i == Integer.MIN_VALUE)
            return "-2147483648";
        //计算整数i的位数
        int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
        char[] buf = new char[size];
        /**
         * 将代表整数i的字符放入字符数组buf
         * 字符从指定索引处的最低有效数字(不包括最高位字符)开始向后放置
         */
        getChars(i, size, buf);
        return new String(buf, true);
    }
    
    final static int [] sizeTable = {
    
    9,99,999,9999,99999,999999,9999999,99999999,999999999,Integer.MAX_VALUE};
    
    static int stringSize(int x) {
    
    
        for (int i = 0; ; i++)
            if (x <= sizeTable[i])
                return i + 1;
    }
}

Analyse du code source Lors du
calcul de la longueur d'un nombre entier, un tableau unidimensionnel est construit, puis le nombre entier est comparé à chaque valeur du tableau. Cependant, la méthode de division fréquemment utilisée n'est pas utilisée pour calculer la longueur. Cela est dû au fait que le calcul de l'efficacité de division par l'ordinateur est inférieur à celui de l'addition, de la soustraction et de la multiplication. Afin d'éviter la division et d'améliorer l'efficacité du calcul, cette méthode est adoptée.

Résumé
Lors du calcul de la longueur d'un certain nombre, vous pouvez vous référer à la méthode stringSize () de la classe Integer.

3. code source d' IntegerCache

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

    static {
    
    
        int h = 127;
         //缓存的最大值是VM参数里java.lang.Integer.IntegerCache.high这个属性
        String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
    
    
            try {
    
    
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                //最大数组大小为Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low) - 1);
            } catch (NumberFormatException nfe) {
    
    
     			//如果无法将属性解析为int,则忽略它
            }
        }
        high = h;

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

        assert Integer.IntegerCache.high >= 127;
    }

    private IntegerCache() {
    
    
    }
}

Analyse du code source

  1. Après avoir initialisé Integer, IntegerCache mettra en cache les données entre [-128,127]. La limite supérieure de cet intervalle peut être configurée et dépend de l'attribut java.lang.Integer.IntegerCache.high. Cet attribut peut être utilisé dans la VM -XX: AutoBoxCacheMax = 2000 Ou -Djava.lang.Integer.IntegerCache.high = 2000 pour ajuster.
  2. Les données de cette plage sont plus couramment utilisées. L'ajout d'un cache peut améliorer les performances et il n'est pas nécessaire d'en créer un à chaque fois, ce qui gaspille les ressources système. En même temps, selon la méthode hashCode d'Integer, vous pouvez voir que le hashCode d'Integer renvoie sa propre valeur int.

Point d'entretien

//程序1-2
public class App {
    
    
    public static void main(String[] args) {
    
    
        Integer a = 1;
        Integer b = 1;
        Integer c = new Integer(1);
        Integer d = 1000;
        Integer e = 1000;
        System.out.println(a == b);//true
        System.out.println(b == c);//false
        System.out.println(d == e);//false
    }
}

4.valueOf et code source parseInt

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

	public static int parseInt(String s) throws NumberFormatException {
    
    
        return parseInt(s,10);
    }
    
    public static int parseInt(String s, int radix) throws NumberFormatException {
    
    
        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') {
    
    
                if (firstChar == '-') {
    
    
                    negative = true;
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != '+')
                    throw NumberFormatException.forInputString(s);

                if (len == 1)
                    throw NumberFormatException.forInputString(s);
                i++;
            }
            multmin = limit / radix;
            while (i < len) {
    
    
                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;
    }
}

Analyse du code source

  1. La méthode valueOf récupérera la valeur du cache, si elle atteint le cache, elle réduira la surcharge des ressources.
  2. La méthode parseInt effectuera d'abord la gestion des exceptions, puis déterminera si la chaîne entrante a un signe, après avoir intercepté le nombre de bits, utilise la multiplication et la soustraction pour obtenir la valeur int, puis détermine le signe et renvoie le résultat.

Je suppose que tu aimes

Origine blog.csdn.net/Jgx1214/article/details/109054058
conseillé
Classement