
包装类就是这8种数据类型所对应的引用数据类型,分别是:

;
inta=num;这种情况就是所谓的自动拆箱,其实底层是调用Integer包装类的intValue()方法,返回了记录的数据值23。以此类推,如果是Double,底层就是调用的doubleValue()方法获取数据值返回4. 常见操作基本数据类型转字符串:静态方法:toString(基本数据类型的数据值),例如:String str = Integer.toString(23);推荐使用String的静态方法:valueOf(基本数据类型的数据值),例如:String str = String.valueOf(20);数值内容的字符串转基本数据类型:调用parseXXX的方法,例如:int num = Integer.parseInt(“66”);注意:如果字符串不是数值内容,而是”a”、”b”、”中”…这样的非数值,就会引发异常:NumberFormatException5. 面试题观察以下代码,说结果Integer a = 127; Integer b = 127; System.out.println(a == b); Integer c = Integer.valueOf(127); System.out.println(a == c); Integer d = new Integer(127); System.out.println(a == d); Integer x = 128; Integer y = 128; System.out.println(x == y);结果分别是:true,true,false,false原因:Integer自动装箱底层会调用valueOf()方法,源代码:publicstaticIntegervalueOf(inti) {
if (i>=IntegerCache.low&&i<=IntegerCache.high)
returnIntegerCache.cache[i+ (–IntegerCache.low)];
returnnewInteger(i);
} 可以看到,会拿数据值和Integer的一个静态内部类IntegerCache类的low属性于high属性做范围判断,其中low的值是-128,high的值是127也就是说,调用valueOf()方法,会判断数据是否在-128~127的范围内。如果在范围内,就从静态内部类IntegerCache的一个cache数组属性中获取一个Integer对象如果不在这个范围内,就是新new一个Integer对象IntegerCache这个静态内部类有一个静态代码块:static{
// high value may be configured by propertyinth=127;
StringintegerCacheHighPropValue=VM.getSavedProperty(“java.lang.Integer.IntegerCache.high”);
if (integerCacheHighPropValue!=null) {
try{
h=Math.max(parseInt(integerCacheHighPropValue), 127);
// Maximum array size is Integer.MAX_VALUEh=Math.min(h, Integer.MAX_VALUE– (–low) –1);
} catch( NumberFormatExceptionnfe) {
// If the property cannot be parsed into an int, ignore it.}
}
high=h;
// Load IntegerCache.archivedCache from archive, if possibleCDS.initializeFromArchive(IntegerCache.class);
intsize= (high–low) +1;
// Use the archived cache if it exists and is large enoughif (archivedCache==null||size>archivedCache.length) {
Integer[] c=newInteger[size];
intj=low;
for(inti=0; i<c.length; i++) {
c[i] =newInteger(j++);
}
archivedCache=c;
}
cache=archivedCache;
// range [-128, 127] must be interned (JLS7 5.1.7)assertIntegerCache.high>=127;
} 一般情况下,这段代码第一个if不会进入,所以high的值就被赋值127,经过计算,size变量的值就是256第二个if语句的条件通常是可以成立的,所以就创建了一个长度为256的Integer类型数组,通过一个for循环,给这个数组就从-128开始赋值,一致赋值到127结束,刚好是256个至此,内部类中就出现了一个Integer类型数组,缓冲了256个Integer对象,对应的数据范围正好是:-128~127那么通过以上分析可知,只要是通过自动装箱或者valueOf()方法去获取对象,只要数据范围在-128~127,不管获取多少次,都会从数组中去拿缓冲的对象,所以拿到的始终是同一个,所以判断的结果就是true但如果不在这个范围内,就是去new一个新的Integer对象,会开辟一个新的对象空间,地址值肯定不一样,所以结果就是false免责声明:文章内容来自互联网,本站仅作为分享,不对其真实性负责,如有侵权等情况,请与本站联系删除。
转载请注明出处:Java教程之包装类详解 https://www.dachanpin.com/a/cyfx/11705.html