[653] in java-interest
Re: Unions
daemon@ATHENA.MIT.EDU (Michael Lorton)
Tue Jul 11 21:57:29 1995
Date: Tue, 11 Jul 1995 17:35:03 -0700
From: Michael Lorton <mlorton@eshop.com>
To: java-interest@java.sun.com
In-Reply-To: Neil Galarneau's message of Tue, 11 Jul 95 16:30:41 EDT <9507112030.AA16073@pinta.bedford.progress.COM>
> This is pretty ugly; anybody got any other sugestions? Of course,
> it's easy to wimp out of the typespace altogether -
>
> class a_union {
> public int tag;
> Object item;
> };
>
> - but this is cheating.
>
> Simon
It is certainly a lot less helpful than the C union.
The C union had the advantage of type checking. His example only allowed
for the union to hold ints and strings. Class a_union allows every object
in the world to be in the union.
Haven't compilied this, but here goes:
class m_union {
private
Vector legalClasses = new Vector();
boolean isLegal(Class c) {
return (legalClasses.indexOf(c) != -1);
}
Object item = null;
public
void legalClass(String className) {
isLegal.addElement(Class.forName(className));
}
void assign(Object newItem) {
if (isLegal(newItem.getClass())) {
item = newItem;
}
else {
throw <something>
}
}
Object itemOf() {
return item;
}
};
Better, I suppose, to develop a general-purpose type-checker and tack
that on (and reuse it for type-checked Vectors and so forth).
M.
-
Note to Sun employees: this is an EXTERNAL mailing list!
Info: send 'help' to java-interest-request@java.sun.com