The following sample code (SSCCE) complains that the local variable a must be final.
public class Foo {
final List<A> list = new ArrayList() {{ add(new A()); }};
void foo() {
A a;
Thread t = new Thread(new Runnable() {
public void run() {
a = list.get(0);
}
});
t.start();
t.join(0);
System.out.println(a);
}
class A {}
}
To make everything work, I change the code to this
public class Foo {
final List<A> list = new ArrayList() {{ add(new A()); }};
void foo() {
final ObjectRef x = new ObjectRef();
Thread t = new Thread(new Runnable() {
public void run() {
x.set(list.get(0));
}
});
t.start();
t.join(0);
System.out.println(x.get());
}
class A {}
class ObjectRef<T> {
T x;
public ObjectRef() {}
public ObjectRef(T x) { this.x = x; }
public void set(T x) { this.x = x; }
public T get() { return x; }
}
}
My questions:
- Is there something wrong with this?
- Does the ObjectRef class exist as a standard class in JSE?
- What is the right way?
source
share