自动装箱和拆箱
package 自动装箱和拆箱;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
/**
* @author hg
* @version 1.0
* @date 2022/5/10 21:25
*/
public class Test {
public static void main(String[] args)
int i=10;//基本数据类型
Integer ii=10;//引用数据类型
Integer integer=new Integer(10);//自动装箱boxing,
int s=integer.intValue();//自动拆箱
//等价于int s=10;
System.out.println(s);
Integer i1=100;
Integer i2=100;
Integer i3=200;
Integer i4=200;
System.out.println(i1==i2);//true??因为在方法区内存中已经存在-128~127的数,
// private static class IntegerCache{}中初始化了一个Integer数组
// 所以当i在-128~127之间。就会直接返回一个cache[]数组中的对象。
System.out.println(i3==i4);//false??当i不在-128~127之间。会返回一个new Integer().
// 所以属于两个不同的对象,就不相等。
//Short,Byte,Character,Long类似只不过大小有点区别
Double d1=100.0;
Double d2=100.0;
Double d3=200.0;
Double d4=200.0;
System.out.println(d1==d2);//false??在类Double中
// 没有Integer中类似于IntegerCache{}。
// 而是 public static Double valueOf(String s) throws NumberFormatException {
// return new Double(parseDouble(s));
// }所以始终是不同的对象
//Float类似。
System.out.println(d3==d4);//false
}
}
//为什么System.out.println(i1==i2);会输出true???
//System是一个类,在类中有public final static printStream out = null;
//printStream又是一个类, 其中有println方法。
//public void println() { newLine();}
// public void println(int x) {
// synchronized (this) {
// print(x);
// newLine();
// }
// }
// public void println(boolean x) {
// synchronized (this) {
// print(x);
// newLine();
// }
// }·····
// 我们可以看到print(x);
// public void print(char c) {
// write(String.valueOf(c));
// public void print(boolean b) {
// write(b ? "true" : "false");
// }
// public static String valueOf(int i) {
// return Integer.toString(i);
// }
//
private static class IntegerCache {}源码如下
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
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);
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
}
}
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 IntegerCache.high >= 127;
}