- valueOf - Wrapper वर्ग में कनवर्ट करता है
- parseInt - आदिम प्रकार में परिवर्तित होता है
Integer.parseInt केवल स्ट्रिंग स्वीकार करते हैं और आदिम पूर्णांक प्रकार (int) वापस करते हैं।
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
Iteger.valueOf int और स्ट्रिंग को स्वीकार करते हैं। यदि मान स्ट्रिंग है, मान इसे parseInt का उपयोग करके सरल इंट में बदल देता है और इनपुट से -128 या 127 से अधिक होने पर नया इंटेगर वापस लौटाता है। यदि इनपुट रेंज में है (-128 - 127) तो यह हमेशा इंटीजर ऑब्जेक्ट को वापस लौटाता है आंतरिक IntegerCache। Integer वर्ग एक आंतरिक स्थैतिक IntegerCache वर्ग को बनाए रखता है जो कैश के रूप में कार्य करता है और -128 से 127 तक पूर्णांक ऑब्जेक्ट रखता है और इसीलिए जब हम 127 के लिए पूर्णांक ऑब्जेक्ट प्राप्त करने का प्रयास करते हैं (उदाहरण के लिए) हमें हमेशा एक ही ऑब्जेक्ट मिलता है।
Iteger.valueOf(200)200 से नया इंटेगर देगा। जैसा new Integer(200)
Iteger.valueOf(127)है वैसा ही है Integer = 127;
यदि आप String को Integer उपयोग में बदलना चाहते हैं 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.valueOf (128) == Integer.valueOf (128) गलत है, क्योंकि 128 IntegerCache रेंज से बाहर है और यह नया Integer लौटाता है, इसलिए वस्तुओं का अलग-अलग संदर्भ होगा।