java - Is it ever justified to have an object which has itself as a field? -
is ever justified have object has field :
class thing { thing field; public thing() { this.field = this; } }
i'm not talking class field of same type class made every instance of class has field. saw in legacy code (this field never used) i'm curious. legit use of ?
yes, though rare. used in jdk situations field this
might not be.
from class implements collections.synchronizedcollection(c)
static class synchronizedcollection<e> implements collection<e>, serializable { private static final long serialversionuid = 3053995032091335093l; final collection<e> c; // backing collection final object mutex; // object on synchronize synchronizedcollection(collection<e> c) { this.c = objects.requirenonnull(c); mutex = this; } synchronizedcollection(collection<e> c, object mutex) { this.c = objects.requirenonnull(c); this.mutex = objects.requirenonnull(mutex); }
in case mutex
might current class, if collection obtained existing synchronised collection, mutex might different. e.g. if call map.values()
, map
synchronizedmap
mutex
map not collection.
another example throwable points cause default.
/** * throwable caused throwable thrown, or null if * throwable not caused throwable, or if causative * throwable unknown. if field equal throwable itself, * indicates cause of throwable has not yet been * initialized. * * @serial * @since 1.4 */ private throwable cause = this;
Comments
Post a Comment