OOP*_*OOP 16 java autoboxing integer
public class Main {
/**
* @param args the command line arguments */
public static void main(String[] args) {
// TODO code application logic here
int a1 = 1000, a2 = 1000;
System.out.println(a1==a2);//=>true
Integer b1 = 1000, b2 = 1000;
System.out.println(b1 == b2);//=>false
Integer c1 = 100, c2 = 100;
System.out.println(c1 == c2);//=>true
}
}
Run Code Online (Sandbox Code Playgroud)
为什么是b1 == b2
虚假和c1 == c2
真实的?
Sea*_*oyd 11
已经给出了正确的答案.但只是加上我的两分钱:
Integer b1 = 1000, b2 = 1000;
Run Code Online (Sandbox Code Playgroud)
这是糟糕的代码.应通过构造函数或工厂方法将对象初始化为对象.例如
// let java decide if a new object must be created or one is taken from the pool
Integer b1 = Integer.valueOf(1000);
Run Code Online (Sandbox Code Playgroud)
要么
// always use a new object
Integer b2 = new Integer(1000);
Run Code Online (Sandbox Code Playgroud)
这段代码
Integer b1 = 1000, b2 = 1000;
Run Code Online (Sandbox Code Playgroud)
另一方面,暗示Integer是一个原始的,它不是.实际上你所看到的是一条捷径
Integer b1 = Integer.valueOf(1000), b2 = Integer.valueOf(1000);
Run Code Online (Sandbox Code Playgroud)
和Integer只汇集-127到127之间的对象,因此在这种情况下它将创建两个新对象.因此,虽然1000 = 1000,但是b1!= b2.这是我讨厌自动拳击的主要原因.
归档时间: |
|
查看次数: |
4778 次 |
最近记录: |