- valueOf - перетворюється в клас Wrapper
- parseInt - перетворює на примітивний тип
Integer.parseInt приймає тільки рядок і повертає примітивний цілочисельний тип (int).
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
Iteger.valueOf приймати int та String. Якщо значення є String, valueOf перетворить його в простий int за допомогою parseInt і поверне новий Integer, якщо вхід менше -128 або більше 127. Якщо вхід знаходиться в діапазоні (-128 - 127), воно завжди повертає об'єкти Integer з внутрішній IntegerCache. Клас Integer підтримує внутрішній статичний клас IntegerCache, який діє як кеш і містить цілі об'єкти від -128 до 127, і тому, коли ми намагаємося отримати цілий об'єкт для 127 (наприклад), ми завжди отримуємо той самий об'єкт.
Iteger.valueOf(200)
дасть новий Integer від 200. Це схоже new Integer(200)
Iteger.valueOf(127)
на те, що Integer = 127
;
Якщо ви не хочете конвертувати String у цілісне використання Iteger.valueOf
.
Якщо ви не хочете перетворити String в просте використання int Integer.parseInt
. Це працює швидше.
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() {}
}
І порівнюючи Integer.valueOf (127) == Integer.valueOf (127) повернути істину
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
Тому що він бере об'єкти Integer з однаковими посиланнями з кеша.
Але Integer.valueOf (128) == Integer.valueOf (128) помилково, оскільки 128 знаходиться поза діапазоном IntegerCache, і він повертає новий Integer, тому об’єкти матимуть різні посилання.