- valueOf - convertit en classe Wrapper
- parseInt - convertit en type primitif
Integer.parseInt n'accepte que String et retourne le type entier primitif (int).
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
Iteger.valueOf accepte int et String. Si la valeur est String, valueOf la convertit en simple int à l'aide de parseInt et renvoie un nouvel entier si l'entrée est inférieure à -128 ou supérieure à 127. Si l'entrée est dans la plage (-128 - 127), elle renvoie toujours les objets Integer à partir d'un IntegerCache interne. La classe Integer maintient une classe IntegerCache statique interne qui agit comme cache et contient les objets entiers de -128 à 127 et c'est pourquoi lorsque nous essayons d'obtenir un objet entier pour 127 (par exemple), nous obtenons toujours le même objet.
Iteger.valueOf(200)
donnera un nouvel Integer à partir de 200. C'est comme new Integer(200)
Iteger.valueOf(127)
est le même que Integer = 127
;
Si vous ne convertissez pas String en entier, utilisez-le Iteger.valueOf
.
Si vous ne voulez pas convertir String en simple int Integer.parseInt
. Ça marche plus vite.
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
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() {}
}
Et en comparant Integer.valueOf (127) == Integer.valueOf (127) renvoie true
Integer a = 127; // Compiler converts this line to Integer a = Integer.valueOf(127);
Integer b = 127; // Compiler converts this line to Integer b = Integer.valueOf(127);
a == b; // return true
Parce qu'il prend les objets Integer avec les mêmes références du cache.
Mais Integer.valueOf (128) == Integer.valueOf (128) est faux, car 128 est hors de la plage IntegerCache et il renvoie un nouvel Integer, donc les objets auront des références différentes.