Vin*_*ent 4 java memory reference
我们考虑以下代码:
public class Testing {
static int i = 47;
public static void main(String[] args) {
Testing t1 = new Testing();
Testing t2 = new Testing();
System.out.println(t1.i == t2.i);
Run Code Online (Sandbox Code Playgroud)
我创建属于测试类的静态字段,这个字段是类的两个实例共享t1,并t2为好.然后我测试它们是否在内存中引用相同的值,实际上,它们确实如此,结果是真的.这对我来说很清楚.
但是,如果我从声明中删除static关键字,则会int i发生意外情况.
public class Testing {
int i = 47;
public static void main(String[] args) {
Testing t1 = new Testing();
Testing t2 = new Testing();
System.out.println(t1.i == t2.i);
Run Code Online (Sandbox Code Playgroud)
我希望两个实例t1和t2对都有47作为其字段的值,但他们的领域是不同的内存地址.但令人惊讶的是,t1.i == t2.i在这种情况下,当我对我的测试成真时 - 为什么?该字段int i = 47;不再是静态的,所以我希望它对于类的每个实例都在不同的内存地址中,但是相等性为真.
An int是基本类型,而不是引用类型.条件t1.i == t2.i不测试参考相等性 - 这里首先没有参考.它只是比较值,在这种情况下,两者都有值47.
如果您的成员字段不是原始字段,则结果会有所不同,例如:
public class Testing {
Integer i = new Integer(47);
public static void main(String[] args) {
Testing t1 = new Testing();
Testing t2 = new Testing();
System.out.println(t1.i == t2.i); // false
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,每个实例对Integer使用new调用构造函数的关键字创建的对象具有不同的引用,并且条件t1.i == t2.i比较这两个引用.