如何一次更改类的所有实例的实例变量,Java
我希望一个类有多个实例,但能够一次更改一个变量的所有非静态实例。也许这段代码会更清楚:如何一次更改类的所有实例的实例变量,Java,java,class,static,instance,non-static,Java,Class,Static,Instance,Non Static,我希望一个类有多个实例,但能够一次更改一个变量的所有非静态实例。也许这段代码会更清楚: public class Example { public int _x; //_x and _y are NOT static public int _y; Example (int x, int y) { _x = x; _y = y; } public void zeroThem() { _x = 0; _y =
public class Example {
public int _x; //_x and _y are NOT static
public int _y;
Example (int x, int y) {
_x = x;
_y = y;
}
public void zeroThem() {
_x = 0;
_y = 0;
}
}
zerothems()
方法的要点是我可能
Example A = new Example(1, 2);
Example B = new Example(3, 4);
但有一次我打电话给这样的人:
A.zerothems()代码>
以下是事实:
A._x == 0;
B._x == 0;
A._y == 0;
B._y == 0;
是否有任何方法可以在不使_x和_y静态的情况下执行此操作?这可以通过以下修复来实现:
您的实例变量需要是易变的
您需要静态同步收集Example
实例并对其进行迭代
根据您的请求,您需要让方法zeroAll
调用实例方法zeroThem
zeroAll
可以实现为非静态,但一旦它影响到Example
的所有实例,最好将其标记为static
是的,如果你在一个集合中有你的对象,那么你可以循环该集合(或使用流)并将所有对象归零。这种设计似乎不正确。这是你真正的问题,还是你试图实现其他目标,而这只是一个演示?如果是这样,也许添加一些真实的上下文可以帮助我们更好地帮助您。如果是这样使用的话,也许您应该首先将字段设置为static
。您需要OP将实例变量设置为volatile,但然后在类级别使用非线程安全的集合is实例-这没有什么意义。如果没有一些非常复杂的东西,比如ReferenceQueue
,您在这里构建的是内存泄漏。@BoristheSpider,您是对的,谢谢您指出这些问题。我更新了答案以回应您的评论。
public class Example {
private static List<Example> all = Collections.synchronizedList(
new ArrayList<>());
public volatile int _x; //_x and _y are NOT static
public volatile int _y;
Example (int x, int y) {
this._x = x;
this._y = y;
Example.all.add(this);
}
public void zeroThem() {
_x = 0;
_y = 0;
}
public static void zeroAll() {
synchronized(Example.all) {
Example.all.forEach(Example::zeroThem);
}
}
}
import java.lang.ref.*;
import java.util.*;
public class Example {
private static final ReferenceQueue<Example> refQueue = new ReferenceQueue<>();
private static final List<WeakReference<Example>> all = Collections.synchronizedList(new ArrayList<>());
public volatile int _x; //_x and _y are NOT static
public volatile int _y;
Example (int x, int y) {
this._x = x;
this._y = y;
Example.all.add(new WeakReference<>(this, refQueue));
}
public void zeroThem() {
_x = 0;
_y = 0;
}
public static void zeroAll() {
synchronized(Example.all) {
Example.all.removeIf(ref -> ref.get() == null); // delete non-existing instances
Example.all
.stream()
.map(WeakReference::get)
.forEach(Example::zeroThem);
}
}
}