What's a reasonable way to mutate a primitive variable from an anonymous Java class?
Posted
by Steve
on Stack Overflow
See other posts from Stack Overflow
or by Steve
Published on 2010-05-04T02:42:03Z
Indexed on
2010/05/04
2:48 UTC
Read the original article
Hit count: 259
I would like to write the following code:
boolean found = false;
search(new SearchCallback() {
@Override void onFound(Object o) { found = true; }
});
Obviously this is not allowed, since found
needs to be final
. I can't make found
a member field for thread-safety reasons. What is the best alternative? One workaround is to define
final class MutableReference<T> {
private T value;
MutableReference(T value) { this.value = value; }
T get() { return value; }
void set(T value) { this.value = value; }
}
but this ends up taking a lot of space when formatted properly, and I'd rather not reinvent the wheel if at all possible. I could use a List<Boolean>
with a single element (either mutating that element, or else emptying the list) or even a Boolean[1]
. But everything seems to smell funny, since none of the options are being used as they were intended.
What is a reasonable way to do this?
© Stack Overflow or respective owner