# 从Integer切入装箱与拆箱

## jdk版本问题

jdk1.5之前创建Integer对象需要如下代码

Integer i1 = new Integer(1);


Integer i1 = 1;


public class IntegerDemo {
public static void main(String[] args) {
Integer i1 = 1;
int a = i1.intValue();
}
}


public class IntegerDemo {
public static void main(String[] args) {
Integer i1 = 1;
int a = i1;
}
}


## 如何实现自动装箱和自动拆箱

public class IntegerDemo {
public static void main(String[] args) {
Integer i1 = 1;
int i = i1;
}
}


## 面试中关于装箱和拆箱的问题

public class IntegerDemo {
public static void main(String[] args) {
Integer i1 = 50;
Integer i2 = 50;
Integer i3 = 200;
Integer i4 = 200;
Integer i5 = new Integer(50);
Integer i6 = new Integer(50);
System.out.println(i1 == i2); // true
System.out.println(i3 == i4); // false
System.out.println(i3.equals(i4)); // true
System.out.println(i5 == i6); // false
System.out.println(i1 == i5); // false
System.out.println(i1.equals(i5)); // true
}
}


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;
}

private IntegerCache() {}
}


public class IntegerDemo {
public static void main(String[] args) {
Integer i1 = 1;
Integer i2 = 2;
Long l1 = 1L;
Long l2 = 2L;
Long l3 = 3L;
System.out.println(l3 == (i1 + i2)); // true
System.out.println(l3.equals(i1 + i2)); // false
}
}


Integer的equals方法

    public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}


Long的equals方法

    public boolean equals(Object obj) {
if (obj instanceof Long) {
return value == ((Long)obj).longValue();
}
return false;
}


public class IntegerDemo {
public static void main(String[] args) {
Double d1 = 1.0;
Double d2 = 1.0;
System.out.println(d1 == d2);   //false
}
}


Boolean包装类

public class IntegerDemo {
public static void main(String[] args) {
Boolean b1 = false;
Boolean b2 = false;
Boolean b3 = true;
Boolean b4 = true;
System.out.println(b1 == b2); // true
System.out.println(b3 == b4); // true
System.out.println(b1 == b3); // false
}
}



 public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);


    public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}


• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 0
评论

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。