包装类型
包装类型
int 与Integer 的区别
这里我们以
Integer i = new Integer(100);
Integer j = new Integer(100);
System.out.print(i == j); //false
因为
/**
* 比较非new生成的Integer变量与new生成的Integer变量
*/
public class Test {
public static void main(String[] args) {
Integer i= new Integer(200);
Integer j = 200;
System.out.print(i == j);
//输出:false
}
}
因为非
/**
* 比较两个非new生成的Integer变量
*/
public class Test {
public static void main(String[] args) {
Integer i1 = 127;
Integer ji = 127;
System.out.println(i1 == ji);//输出:true
Integer i2 = 128;
Integer j2 = 128;
System.out.println(i2 == j2);//输出:false
}
}
/**
* 比较Integer变量与int变量
*/
public class Test {
public static void main(String[] args) {
Integer i1 = 200;
Integer i2 = new Integer(200);
int j = 200;
System.out.println(i1 == j);//输出:true
System.out.println(i2 == j);//输出:true
}
}
包装类
自动包装与拆包
Integer a = 1;
Integer a = Integer.valueOf(1);
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
当
IntegerCache.cache[i + (-IntegerCache.low)]
因此
Integer a = 1;
Integer b = 1;