我正在看Thinking in java这本书,挺有意思的,书里有一个例子,例子的行为和输出结果和我预想的不一样。
示例:
package net.mindview.util;
import static net.mindview.util.Print.*;
class Shared {
private int refcount = 0;
private static long counter = 0;
private final long id = counter++;
public Shared() {
print("Creating " + this);
}
public void addRef() {
refcount++;
}
protected void dispose() {
if (--refcount == 0)
print("Disposing " + this);
}
public String toString() {
System.out.println(id);
return "Shared " + id;
}
}
class Composing {
private Shared shared;
private static long counter = 0;
private final long id = counter++;
public Composing(Shared shared) {
print("Creating " + this);
this.shared = shared;
this.shared.addRef();
}
protected void dispose() {
print("disposing " + this);
shared.dispose();
}
public String toString() {
return "Composing " + id;
}
}
public class ReferenceCounting {
public static void main(String[] args) {
Shared shared = new Shared();
Composing[] composing = { new Composing(shared), new Composing(shared),
new Composing(shared), new Composing(shared),
new Composing(shared) };
for (Composing c : composing)
c.dispose();
}
}
这是一个dispose方法的例子,我完全理解,我的问题是Shared类中id的值。
正如我从 Thinking in java 中学习的那样,字段和对象的初始化应该发生在任何方法被调用之前,甚至是构造函数,但是 Shared 类的构造函数的输出是“Creating Shared 0”,其值为id 被认为是 0,尽管 private final long id = counter++;
已经占据一席之地,现在我想 id 值应该是 1 而不是零。谁能向我解释一下这种行为。
最佳答案
counter++
是后递增的,这意味着值是在之前递增赋值的。另一侧的预增量将显示您预期的行为。
关于java - 当 i++ 操作的值发生并存储在它在 Java 中的引用中时..?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30856398/